JAVA learning 10-29 -- rewriting, super, polymorphism

Keywords: Java Back-end

Method override

  • 1. Override: after a subclass inherits the parent class, it can override the methods in the parent class.
  • 2. Application: after rewriting, when a subclass object is created and a method with the same name and parameter in the child parent class is called through the subclass object, the method of overriding the parent class by the subclass is executed.
    That is, when the program is executed, the methods of the child class will override the methods of the parent class.
  • 3. Rewriting provisions:
    Method declaration: permission modifier return value type method name (formal parameter list){
    //Method body
    }
    Conventions are commonly known as overridden methods in subclasses and overridden methods in parent classes.
  • ① The method name and parameter list of the method overridden by the subclass must be the same as the method name and parameter list of the method overridden by the parent class;
  • ② The access permission of the method overridden by the subclass cannot be less than that of the method overridden by the parent class,
    Special case: the subclass cannot override the method declared as private permission in the parent class; (the permission is too small for the subclass to see, so it doesn't matter to override)
  • ③ Return value type:
    If the return value type of the method overridden by the parent class is void, the return value type of the method overridden by the child class can only be void;
    If the return value type of the method overridden by the parent class is type A, the return value type of the method overridden by the child class can be class A or a subclass of class A;
    If the return value type of the method overridden by the parent class is a basic data type (for example, double), the return value type of the method overridden by the child class must be the same basic data type (must be: double).
  • ④ The exception thrown by the subclass method cannot be greater than the exception thrown by the overridden method of the parent class;
    Note: methods with the same name and parameters in the subclass and the parent class must be declared non static (that is, overridden) or static (not overridden) at the same time. Because static methods belong to classes, subclasses cannot override the methods of the parent class.

Interview question: distinguish between overloading and rewriting of methods (some books are also called "coverage")

A: Overriding and Overloading of methods are different manifestations of Java polymorphism.
Overriding is a manifestation of polymorphism between parent and child classes, and Overloading is a manifestation of polymorphism in a class.
If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overridden.
When an object of a subclass uses this method, the definition in the subclass will be called. For it, the definition in the parent class is "masked".
If multiple methods with the same name are defined in a class, they either have different parameter numbers or different parameter types, it is called method overloading.

super keyword

Use of super keyword

  • 1.super is understood as the parent class
  • 2.super can be used to call: properties, methods and constructors
  • 3. Use of super
  • 3.1 we can explicitly call in subclass methods or constructors by means of "super. Attribute" or "super. Method"
    Properties or methods declared in the parent class. However, usually, we are used to omitting this "super."
  • 3.2 special case: when the properties of the same name are defined in the subclass and the parent class, if we want to call the properties declared in the parent class in the subclass, we must explicitly use the "super. attribute" method to indicate that the properties declared in the parent class are invoked.
  • 3.3 special case: when a child rewrites the method in the parent class, we want to call the rewritten method in the parent class when we want to call the method in the subclass. We must explicitly use the "super. method" to indicate that the method that is rewritten in the parent class is invoked.
    4.super call constructor
  • 4.1 we can explicitly use "super (formal parameter list)" in the constructor of the subclass to call the specified constructor declared in the parent class
  • 4.2 the use of "super (formal parameter list)" must be declared in the first line of the subclass constructor!
  • 4.3 in the class constructor, we can only choose one of "this" or "super" and cannot appear at the same time.
  • 4.4 if there is no explicit declaration of "this" or "super" in the first line of the constructor, the null parameter constructor in the parent class will be called by default. super()
  • 4.5 among multiple constructors of a class, the constructor of at least one class uses "super (formal parameter list)" to call the constructor in the parent class.

Person class

public class Person {

	String name;
	int age;
	int id = 1003;	//ID number
	
	public Person(){
		System.out.println("I'm everywhere");
	}
	
	public Person(String name){
		this.name = name;
	}
	
	public Person(String name,int age){
		this(name);
		this.age = age;
	}
	
	public void eat(){
		System.out.println("People, eat");
	}
	
	public void walk(){
		System.out.println("People, walk");
	}
}

Student class

public class Student extends Person{
	
	String major;
	int id = 1002;	//Student number
	
	public Student(){

	}
	
	public Student(String name,int age,String major){
//		this.age = age;
//		this.name = name;
		super(name,age);
		this.major = major;
	}
	
	public Student(String major){
		this.major = major;
	}
	
	public void eat(){
		System.out.println("Students eat more nutritious food");
	}
	
	public void Study(){
		System.out.println("Students, learning knowledge.");
		this.eat();
		//If you want to call the overridden method in the parent class and do not want to call the method in the child class, you can:
		super.eat();
		super.walk();//The method not overridden in the child parent class can be called with "this." or "super."
	}
	public void show(){
		System.out.println("name = " + this.name + ",age = " + super.age);
		System.out.println("id = " + this.id);	
		System.out.println("id = " + super.id);
	}
}

Test class

public class SuperTest {
	public static void main(String[] args) {
		
		Student s = new Student(); //I'm everywhere
		s.show();// name=null age =0 id=1002   id=1001
		
		s.Study(); //Students, learn knowledge, students eat more nutritious food, eat more, and walk
		
		Student s1 = new Student("Ton",21,"IT" );
		s1.show();  //name=Tom age =21 id=1002   id=1001
		
		System.out.println("***********************");
		Student s2 = new Student();//I'm everywhere
		
	}
}

Polymorphism

  • 1. Understanding polymorphism: it can be understood as the multiple states of a thing.

  • 2. What is polymorphism
    Object polymorphism: the reference of the parent class points to the object of the child class (or the reference assigned to the parent class by the object of the child class)

  • 3. Use of polymorphism: virtual method call
    With object polymorphism, we can only call the methods declared by the parent class at compile time, but in execution time, we actually execute the methods of the child class overriding the parent class
    Abbreviation: when compiling, look at the left; when running, look at the right.
    If compile time type and run-time type are inconsistent, object polymorphism occurs
    In case of polymorphism,
    "Look at the left": look at the reference of the parent class (the parent class does not have methods unique to the child class)
    "Look at the right": it looks at the objects of the subclass (actually running the methods of the subclass overriding the parent class)

  • 4. Premise of polymorphism:
    ① Class inheritance
    ② Method override

  • 5. Object polymorphism: only applicable to methods, not attributes (see the left for compilation and operation)

Person class

public class Person {
	String name;
	int age;
	int id=1001;
	
	public void eat(){
		System.out.println("People, eat");
	}
	
	public void walk(){
		System.out.println("People, walk");
	}
	
}

Man class

public class Man extends Person{
	
	boolean isSmoking;
	int id=1002;
	public void earnMoney(){
		System.out.println("Men work to support their families");
	}
	
	public void eat() {
		System.out.println("Men eat more meat and grow muscles");
	}
	
	public void walk() {
		System.out.println("Man's domineering walk");
	}
}

Test class

public class PersonTest {
	public static void main(String[] args) {
		
	Person p1 = new Person();
	p1.eat();
	Man man = new Man();
	man.eat();
	man.age = 25;
	man.earnMoney();
	
	//************************************
	//Object polymorphism, the reference of the parent class points to the object of the child class
	Person p2 = new Man();
	//Use of polymorphism: when calling a method with the same name and parameter as the child parent class, what is actually called is the method of the child class overriding the parent class - virtual method call
	p2.eat();//Men eat more meat and grow muscles
	p2.walk();//Man's domineering walk
	
System.out.println(p2.id);//1001
	
	}
}

Application examples of polymorphism

public class AnimalTest {
	
	public static void main(String[] args) {
		AnimalTest test = new AnimalTest();
		test.func(new Dog());//Dogs eat bones
		
		test.func(new Cat());//Cats eat fish, meow meow
	}

	public void func(Animal animal){	//Animal animal = new Dog();
		animal.eat();
		animal.shout();
	}
	
	//If there is no polymorphism, many of the following methods will be written to call
	public void func(Dog dog){
		dog.eat();
		dog.shout();
	}
	
	public void func(Cat cat){
		cat.eat();
		cat.shout();
	}
}

class Animal{
	
	public void eat(){
		System.out.println("Animals, eating");
	}
	
	public void shout(){
		System.out.println("Animal: call");
	}
}

class Dog extends Animal{
	public void eat(){
		System.out.println("Dogs eat bones");
	}
	
	public void shout() {
		System.out.println("Woof! Woof! Woof!");
	}
}

class Cat extends Animal{
	public void eat(){
		System.out.println("Cats eat fish");
	}
	
	public void shout() {
		System.out.println("Meow! Meow! Meow!");
	}
}

Method overloading and overriding

  • From the perspective of compilation and operation:
    Overloading means that multiple methods with the same name are allowed, and the parameters of these methods are different. The compiler modifies the name of the method with the same name according to different parameter tables of the method. For the compiler, these methods with the same name become different methods. Their call addresses are bound at compile time. Java overloading can include parent classes and subclasses, that is, subclasses can overload methods with different parameters of the same name of the parent class. Therefore: for overloads, the compiler has determined the method to be called before the method call, which is called "early binding" or "static binding";
    For polymorphism, the interpreter will not determine the specific method to be called until the moment of method call, which is called "late binding" or "dynamic binding".

  • Quote Bruce Eckel: "don't be silly. If it's not late binding, it's not polymorphic."

  • Interview question: is polymorphism a compile time behavior or a runtime behavior?
    The certificate is as follows:

import java.util.Random;
class Animal  {
 
	protected void eat() {
		System.out.println("animal eat food");
	}
}

class Cat  extends Animal  {
 
	protected void eat() {
		System.out.println("cat eat fish");
	}
}

class Dog  extends Animal  {
 
	public void eat() {
		System.out.println("Dog eat bone");

	}

}

class Sheep  extends Animal  {
 
	public void eat() {
		System.out.println("Sheep eat grass");

	}
 
}

public class InterviewTest {

	public static Animal  getInstance(int key) {
		switch (key) {
		case 0:
			return new Cat ();
		case 1:
			return new Dog ();
		default:
			return new Sheep ();
		}

	}

	public static void main(String[] args) {
		int key = new Random().nextInt(3);

		System.out.println(key);

		Animal  animal = getInstance(key);
		
		animal.eat();
		 
	}

}

Posted by f1nutter on Fri, 29 Oct 2021 05:34:12 -0700