java多态例子

多态存在的三个必要条件
一、要有继承;
二、要有重写;
三、父类引用指向子类对象。

代码部分:

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 {
}

然后开始搞脑子了:

public static void main(String[] args) {
        A a1 = new A();
        A a2 = new B();
        B b = new B();
        C c = new C();
        D d = new D();
        
        System.out.println(a1.show(a1));
        System.out.println(a1.show(a2));
        System.out.println(a2.show(a1));
        System.out.println(a2.show(a2));
        System.out.println(b.show(a1));
        System.out.println(b.show(a2));
        System.out.println(c.show(a1));
        System.out.println(c.show(a2));
        System.out.println(d.show(a1));
        System.out.println(d.show(a2));
        System.out.println("分割线**************************************");
        System.out.println(a1.show(b));
        System.out.println(a1.show(c));
        System.out.println(a1.show(d));
        System.out.println(a2.show(b));
        System.out.println(a2.show(c));
        System.out.println(a2.show(d));
        System.out.println(b.show(b));
        System.out.println(b.show(c));
        System.out.println(b.show(d));
        System.out.println(c.show(b));
        System.out.println(c.show(c));
        System.out.println(c.show(d));

    }

运行结果:

A and A
A and A
B and A
B and A
B and A
B and A
B and A
B and A
B and A
B and A
分割线**************************************
A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
B and B
B and B
A and D

为了方便理解,我列了下每个类的method table

A
show(D) -> A.show(D)
show(A) -> A.show(A)

B,C, D
show(D) -> A.show(D)
show(B) -> B.show(B)
show(A) -> B.show(A)
原文地址:https://www.cnblogs.com/ryansunyu/p/4536543.html