class A {
public void show(D obj){
System.out.println("A and D");
}
public void show(A obj){
System.out.println ("A and A");
}
}
class B extends A{
public void show(B obj){
System.out.println("B and B");
}
public void show(A obj){
System.out.println("B and A");
}
}
class C extends B{}
class D extends B{}
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
a1.show(b);
a1.show(c);
a1.show(d);
a2.show(b);
a2.show(c);
a2.show(d);
b.show(b);
b.show(c);
b.show(d);
答案如下:
A and AA and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
经上机实验,却是如此。下面来解释原因。
对于多态,可以总结以下几点:
一、使用父类类型的引用指向子类的对象;
二、该引用只能调用父类中定义的方法和变量;
三、如果子类中重写了父类中的一个方法,那么在调用这个方法的时候,将会调用子类中的这个方法;(动态连接、动态调用)
四、变量不能被重写(覆盖),”重写“的概念只针对方法,如果在子类中”重写“了父类中的变量,那么在编译时会报错。
五、this(tihs),super(this),this(super),super(super)//多态函数的调用优先级
拿到例子先看两个地方,对象类型和参数类型。
1-3号是一种类型,只分析一个。a1.show(b),对象类型为A,参数类型为B,严格对应的有没有? 没有。那么用第五条,捋到第三个this(super)发现可以匹配,那么输出A and A。
4,5号。a2.show(b),对象类型为B,参数类型为B,严格对应的有吗? 有。但是这个B.(B)在A中没定义,所以不能用。还是得用第五条捋阿,捋到最后,super(super),可以了,但是B已经重写了该方法,所以输出A and B。(对应了第三条)
6号捋到super(this)。
7号严格对应。
8号this(super)。
9号super(this)。