1 class A { 2 public String show(D obj) { // func1 3 return ("A and D"); 4 } 5 public String show(A obj) { // func2 6 return ("A and A"); 7 } 8 } 9 class B extends A { 10 public String show(B obj) { // func3 11 System.out.println("1"); 12 return ("B and B"); 13 } 14 public String show(A obj) { // func4 15 System.out.println("2"); 16 return ("B and A"); 17 } 18 } 19 class C extends B {} 20 class D extends B {} 21 22 public class Main { 23 public static void main(String[] args) { 24 A a1 = new A(); 25 A a2 = new B(); 26 A b = new B(); 27 C c = new C(); 28 D d = new D(); 29 System.out.println(a2.show(b)); 30 } 31 }
输出结果为:"B and A"
类B继承A,所以会从父类A得到函数fun1和fun2,因为fun4和fun2完全一样,故fun4覆盖了fun2,而fun3重载了fun1,故类B实际上有fun1,fun3,fun4三个函数,当给B传入表达式A b = new B() 中的b时,因为new B()向上转型到A,故只能调用fun4的函数,而不会把类型A向下转型到B或D,即不可能调用fun4或fun1.
时间: 2024-10-09 22:28:30