Java polymorphism notes (how to achieve polymorphism)

    Polymorphism refers to the phenomenon of different execution effects caused by different parameter types in the same method is polymorphism. To put it bluntly, different objects will get different results when executing the same method.
    Conditions for achieving polymorphism:

  • There must be inheritance
  • Rewrite
  • The parent class reference points to the child class object
    instance:
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //创建YellowPerson类的实例,是父类的变量引用
        Person yellowPerson = new YellowPerson();
        //创建YellowPerson类的实例,是父类的变量引用
        Person blackPerson = new BlackPerson();
        AA(yellowPerson);
        AA(blackPerson);
    }
    //创建一个静态方法接收Person类型的变量
    public static void AA(Person person) {
    
    
        person.eat();
        person.run();
    }
}
//父类Person
class Person{
    
    
    int height;
    String color;
    //人吃饭的方法
    public void eat(){
    
    
        System.out.println("中国人使用筷子吃饭....");
    }
    //人跑的方法
    public void run(){
    
    
        System.out.println("中国人跑步真厉害....");
    }
}
//YellowPersonS继承父类Person
class YellowPerson extends Person{
    
    
    int height;
    String color;
    //子类重写吃饭的方法
    public void eat(){
    
    
        System.out.println("黄种人在吃饭....");
    }
    //子类重写人跑的方法
    public void run(){
    
    
        System.out.println("黄种人在跑步....");
    }
}
//BlackPerson继承父类Person
class BlackPerson extends Person{
    
    
    int height;
    String color;
    //子类重写吃饭的方法
    public void eat(){
    
    
        System.out.println("黑种人在吃饭....");
    }
    //子类重写人跑的方法
    public void run(){
    
    
        System.out.println("黑种人在跑步....");
    }
}

Operation result: In
Insert picture description here
    Java, except static method and final method (private method belongs to final method) are early binding, all other methods are late binding.

  • The method modified by the final keyword cannot be overridden, that is, to prevent the method from being overwritten by others, and also to avoid dynamic binding.
  • The method modified by the private keyword is not visible to the subclass, and cannot be inherited by the subclass, so private-level methods cannot be called through the subclass object; the only way to call is through the object itself within the class. So, the private-level method is bound to the class that defines this method.
  • The method modified by the static keyword belongs to the class rather than the object, so it cannot be overridden, but the static method can be inherited by the subclass (cannot show polymorphism, because the static method of the parent class will be overwritten by the subclass).

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/109322246