类的继承和多态细思
一、前言
类的继承和多态光靠概念和想象是不够的,我们需要编码去分析之,因此我使用代码来说明一些很难分清的东西。
二、分析代码
A类代码:
package zyr.study.poly; public class A { public A(){ System.out.println("初始化A..."); } public String show(A obj) { return ("A and A"); } public String show(B obj) { return ("A and B"); } public String show(D obj) { return ("A and D"); } }
B类代码:
package zyr.study.poly; public class B extends A{ public B(){ System.out.println("初始化B..."); } public String show(A obj){ return ("B and A"); } public String show(B obj){ return ("B and B"); } }
C类代码:
package zyr.study.poly; public class C extends B{ public C(){ System.out.println("初始化C..."); } }
D类代码:
package zyr.study.poly; public class D extends B{ public D(){ System.out.println("初始化D..."); } }
main函数:
1 package zyr.study.poly; 2 3 4 public class Main { 5 6 public static void main(String[] args) { 7 A a1 = new A(); 8 System.out.println("-----------------"); 9 A a2 = new B(); 10 System.out.println("-----------------"); 11 B b = new B(); 12 System.out.println("-----------------"); 13 C c = new C(); 14 System.out.println("-----------------"); 15 D d = new D(); 16 System.out.println("-----------------"); 17 18 System.out.println("1--" + a1.show(a1)); // a and a 19 System.out.println("2--" + a1.show(a2)); // a and a 20 System.out.println("3--" + a1.show(b)); // a and b 21 System.out.println("4--" + a1.show(c)); // a and b 22 System.out.println("5--" + a1.show(d)); // a and d 23 24 System.out.println("-----------------"); 25 26 System.out.println("1--" + a2.show(a1)); // b and a 27 System.out.println("2--" + a2.show(a2)); // b and a 28 System.out.println("3--" + a2.show(b)); // b and b 29 System.out.println("4--" + a2.show(c)); // b and b 30 System.out.println("5--" + a2.show(d)); // a and d 31 32 System.out.println("-----------------"); 33 34 System.out.println("1--" + b.show(a1)); // b and a 35 System.out.println("2--" + b.show(a2)); // b and a 36 System.out.println("3--" + b.show(b)); // b and b 37 System.out.println("4--" + b.show(c)); // b and b 38 System.out.println("5--" + b.show(d)); // a and d 39 } 40 }
运行结果:
初始化A... ----------------- 初始化A... 初始化B... ----------------- 初始化A... 初始化B... ----------------- 初始化A... 初始化B... 初始化C... ----------------- 初始化A... 初始化B... 初始化D... ----------------- 1--A and A 2--A and A 3--A and B 4--A and B 5--A and D ----------------- 1--B and A 2--B and A 3--B and B 4--B and B 5--A and D ----------------- 1--B and A 2--B and A 3--B and B 4--B and B 5--A and D