四、方法重载,多态,重写综合练习
public class Demo
{
publicstatic 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));//1
System.out.println(a1.show(c));//2
System.out.println(a1.show(d));//3
System.out.println(a2.show(b));//4
System.out.println(a2.show(c));//5
System.out.println(a2.show(d));//6
System.out.println(b.show(b));//7
System.out.println(b.show(c));//8
System.out.println(b.show(d));//9
}
}
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{}
答案: 关键点 调用的时候先去父类中找到方法,然后再去子类中找到子类重写的方法
① 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