Java—polymorphism

  • Polymorphism: One form of expression, multiple realizations.
    Two types: compile-time polymorphism, runtime polymorphism
    1, compile-time polymorphism: specifically expressed as method overloading
    2. Run-time polymorphism: concretely expressed as method rewriting
    The three prerequisites of runtime polymorphism:
    1. ) Inheritance
    2.) Override
    3.) The declaration of the parent class points to the reference of the child class (the object of the child class is created)

  • The Richter Substitution Principle:
    1. When a place needs a parent class object, we can replace it with a subclass object class.
    2. Subclasses cannot override the specific methods of the parent class

Demo type:

public class Demo {
    
    
    public void show(){
    
    
        System.out.println("show()...");
    }

    public void show(int x){
    
    
        System.out.println("show(int x)...");
    }
}

Father class:

public class Father {
    
    
    public void show(){
    
    
        System.out.println("father is showing...");
    }
}

Son type

public class Son extends Father{
    
    
    public void show(){
    
    
        System.out.println("son is showing...");
    }

}

Daughter class:

public class Daughter extends Father{
    
    
    public void show(){
    
    
        System.out.println("daughter is showing...");
    }
}

Test class:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        /**
         * 多态:一种表现形式,多种实现。
         * 两种:编译时多态、运行时多态
         * 编译时多态:具体表现为方法重载
         * 运行时多态:具体表现为方法重写
         * 运行时多态的三大前提条件:
         * 1. 继承
         * 2. 重写
         * 3. 父类的声明指向子类的引用(创建的是子类的对象)
         */

        // 方法重载:编译时多态
        Demo demo=new Demo();
        demo.show();
        demo.show(10);

        // 运行时多态
        // 一个父类可以有多个子类, 具体调用的是哪个方法的重写,由创建的对象决定
        // 父类的声明指向子类的引用
        Father o=new Son();
        o.show();

        o=new Daughter();
        o.show();
        /**
         * 里氏代换原则:
         * 1. 当一个地方需要一个父类对象,我们可以通过子类对象类替代他。
         * 2. 子类不可以重写父类的具体方法
         */

    }
}

operation result:

show()...
show(int x)...
son is showing...
daughter is showing...

Guess you like

Origin blog.csdn.net/qq_44371305/article/details/113181412