今天看到博客园上一位原创的博文讲解Java多态性,觉得不错,不过没有解释,特此注释,侵删

public class MyTest {
    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(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)); a2.name(); } } class A { public void name(){ System.out.println("My Name is A"); } public String show(D obj){ return ("A and D"); } public String show(A obj){ return ("A and A"); } } class B extends A{ public void name(){ System.out.println("My Name is B"); } 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{}

结果是

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
My Name is B

这里主要说一下

A a2 = new B()

关于向上转型:定义了B类,编译器在编译的时候查找A类里面的方法,但是在运行的时候,JVM去运行B类里面的方法,如果B类中不存在就运行A类的方法。
也就是说,执行a2.show(b)时,先去A类中查找,找到show(A obj),运行的时候运行B类中的show(A obj);执行a2.show(d)时,只会执行A类中的show(D obj),因为B类中没有这个方法

posted on 2018-01-22 20:17  东边的疯  阅读(172)  评论(0编辑  收藏  举报