Java三大新特性之一--多态,老大难,估计工作十来年的小伙伴对于多态也有很多玩不明白,笔者也一直蒙圈中,今天找了一个小demo,想对多态有个深入的了解,demo介绍:A类是父类,B类继承A类,重写show(A obj)方法,通过下面各种多态的调用,方便理解对象的多态使用。 static class A { public String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } public A(){ System.out.println("对象A构造..."); } } static class B extends A { public B(){ System.out.println("对象B构造..."); } public String show(B obj) { return ("B and B"); } public String show(A obj) { return ("B and A"); } } static class C extends B { } static class D extends B { } public static void main(String[] args) { A a1 = new A(); System.out.println("初始化1完成"); A a2 = new B(); System.out.println("初始化2完成"); B b = new B(); System.out.println("初始化3完成"); C c = new C(); System.out.println("初始化4完成"); D d = new D(); System.out.println("初始化5完成"); System.out.println("1--" + a1.show(b)); // 1--A and A System.out.println("2--" + a1.show(c)); // 2--A and A System.out.println("3--" + a1.show(d)); // 3--A and D System.out.println("4--" + a2.show(b)); // 4--B and A System.out.println("5--" + a2.show(c)); // 5--B and A System.out.println("6--" + a2.show(d)); // 6--A and D System.out.println("7--" + b.show(b)); // 7--B and B System.out.println("8--" + b.show(c)); // 8--B and B System.out.println("9--" + b.show(d)); // 9--A and D }
通过以上打印结果,总结了一句话:
引用调用方法 优先调用父类的方法 如果父类没有找到 找重载的方法 如果子类重写这个方法了 就调用子类的这个方法 如果父类找不到 也调用子类的重写方法