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{}
//父类引用指向子类对象 只能调用父类中定义的方法和变量;
//如果子类中重写了父类中的一个方法,那么在调用这个方法的时候,将会调用子类中的这个方法;
public class PolymorphismTest{
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)); //① A and A 子类可当做父类的对象
System.out.println(a1.show(c)); // ② 同上
System.out.println(a1.show(d)); // ③ A and D 父类有定义这个方法
System.out.println(a2.show(b)); // ④ B and A
System.out.println(a2.show(c)); // ⑤ B and A
System.out.println(a2.show(d)); //⑥ A and D
System.out.println(b.show(b)); //⑦ B and B
System.out.println(b.show(c)); // ⑧ B and B c对象可当做B类的对象
System.out.println(b.show(d)); // ⑨ A and D B类继承过来有这个方法
}
}
【个人Java笔记】多态2 比较经典的一个例子
最新推荐文章于 2023-04-16 21:08:28 发布