class Father{
public void A(){]
}
class Son extends Father{
public void A(){}
public static void main(){
Father f = new Son();
f.A();
}
}
1. 当子类重写了父类的方法时,f 会调用子类的方法。
class Father{
public void A(int C){]
}
class Son extends Father{
public void A(char C){}
public static void main(){
Father f = new Son();
char C = 'c';
f.A(C);
}
}
2. 注意此处,因为子类中方法的参数类型变了,所以子类中的方法是一个全新的方法,与父类中的毫无关系,所以 f 会去调用父类中的方法。因为与父类中的方法参数类型不一致,此处会自动转型。
class Father{
int b = 10;
public void A(int C){]
}
class Son extends Father{
int b = 20;
public void A(char C){}
public static void main(){
Father f = new Son();
char C = 'c';
f.A(C);
}
}
3. 动态绑定只针对对象的方法,对于成员变量无效,因为成员变量不能被重写。f.b 的值为10。