在查看ArrayList.containsAll方法的源码时发现,ArrayList没有重写containsAll方法,向上查询后发现此方法在AbstractCollection类中有实现。这个AbstractCollection类是ArrayList的父类的父类。关系结构如下图。
在AbstractCollection中代码如下,这个类自己有实现contains方法。
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
同时,ArrayList中也重写了contains方法。由此产生一个疑问:在继承关系中,多态是一个什么情况。父类的引用调用子类对象的方法时,动态绑定是怎么样的。此处的contains是AbstractCollection的方法还是ArrayList的方法。所以特地写了代码验证。
通过以下代码可以得出结论,方法调用是动态绑定到对象。当对象类中有方法时用自己的方法,没有时向上查询。在父类中方法中调用了方法依然是从对象类中开始找,如果没有再层层向上找。
package com.syy.test;
/**
* @author Songyy
* @create 2018-08-04 星期六 16:04
*/
public class Demo_Inherit {
public static void main(String[] args) {
aFather p = new bSon();
p.aMethod();
}
}
class aFather{
private int num;
private int age;
public int aMethod() {
System.out.println("aFather aMethod");
return num;
}
public int bMethod() {
System.out.println("aFather bMethod");
return num;
}
public int cMethod() {
System.out.println("aFather cMethod");
return num;
}
public int dMethod() {
System.out.println("aFather dMethod");
return num;
}
}
class aSon extends aFather {
@Override
public int aMethod() {
System.out.println("aSon aMethod");
bMethod();
cMethod();
dMethod();
return 123;
}
public int cMethod() {
System.out.println("aSon cMethod");
return 123;
}
}
class bSon extends aSon {
@Override
public int bMethod() {
System.out.println("bSon bMethod");
return 324;
}
}
运行结果。
aSon aMethod
bSon bMethod
aSon cMethod
aFather dMethod
Process finished with exit code 0