java基础

Java 多态

2018-09-21  本文已影响4人  韭菜待收割

1、Java 多态分类

1)编译时多态:方法重载。
2)运行时多态:JAVA运行时系统根据调用该方法的实例的类型来决定选择调用哪个方法则被称为运行时多态。

2、运行时多态存在的三个必要条件:

1)要有继承(包括接口的实现);
2)要有重写;
3)父类引用指向子类对象。

3、编译时多态、运行时多态码示例

运行时多态的口诀(super是直接父类、找不到就找父类的父类、以此类推)
优先级由高到低依次为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)

//懒,就写一起了
public class MainTest {

    //测试方法
    public static void main(String[] args) throws Exception {
        MainTest mainTest = new MainTest();
        mainTest.test();
    }
    public void test(){
        A a1 = new A();
        A a2 = new B();
        B b = new B();
        C c = new C();
        D d = new D();
        E e = new E();
        //重载 "A and A"   this.show((super)O)  口诀第三个
        System.out.println(a1.show(b));
        //重载 "A and A"   this.show((super)O)  口诀第三个
        System.out.println(a1.show(c));
        //重载 "A and D"   this.show(O)  口诀第一个
        System.out.println(a1.show(d));

        
        //a2是一个引用变量,类型为A,则this为a2
        //口诀第一个匹配不到、口诀第二个匹配不到、口诀第三个匹配,由于有重写  B and A
        System.out.println(a2.show(b));
        //口诀第三个匹配,由于有重写  B and A  (父类引用指向子类对象考虑重写)
        System.out.println(a2.show(c));
        //A and D  口诀第一个匹配 this.show(O)
        System.out.println(a2.show(d));
        //B and A  口诀第三个匹配,由于有重写  B and A  (父类引用指向子类对象考虑重写)
        System.out.println(a2.show(e));


        //B and B 口诀第一个匹配
        System.out.println(b.show(b));
        //B and B 口诀第三个匹配
        System.out.println(b.show(c));
        //A and D 口诀第二个匹配
        System.out.println(b.show(d));
    }
    class A {
        //重载
        public String show(D obj){
            return ("A and D");
        }
        //重载
        public String show(A obj){
            return ("A and A");
        }
    }

    class B extends A{
        //重载
        public String show(B obj){
            return ("B and B");
        }
        //重写
        public String show(A obj){
            return ("B and A");
        }
    }
    class C extends B{}
    class D extends B{}
    class E extends C{}
}
上一篇 下一篇

猜你喜欢

热点阅读