考虑以下示例:
public class Main
{
public static void main(String[] args) {
System.out.println(new Maruti().howManyTires());
new Maruti().getColor();
}
}
class Car {
private int tires = 1;
public int howManyTires(){
return tires;
}
public void getColor(){
getNiceColour();
}
public void getNiceColour(){
System.out.println("Blue");
}
}
class Maruti extends Car {
private int tires = 10;
public int howManyTires(){
return super.howManyTires();
}
public void getColor(){
super.getColor();
}
public void getNiceColour(){
System.out.println("Magenta");
}
}
输出是:
1
Magenta
我的问题是,当howManyTires通过调用超类的函数时super,this引用显然是子类的(如对该getColor方法的调用所示)。然而,它返回超类tires字段。
我知道字段只是隐藏而不是重写,但是除非这些字段绑定到类(如类变量),否则调用超类的方法howManyTires应该返回tires由this引用(属于子类)绑定的值
慕运维8079593
相关分类