我有一个关于继承的问题。 如果我想从子类中的父类调用一个方法,我应该使用 super.method() 还是 this.method() ?在我编写的程序中,它们都可以工作,所以我同时使用它们,但我并不认为这是正确的方法。
例如,假设我有一个名为“Vehicle”的类,另一个名为“Airplane”。假设我在 Vehicle 中有一个 brand() 方法。我应该使用 this.brand() 还是 super.brand() ?
提前致谢。
答案 0 :(得分:4)
考虑这个代码片段,
class Vehicle {
public void brand(){
System.out.println("This is a vehicle");
}
}
class Airplane extends Vehicle {
public void brand() {
System.out.println("This is an airplane");
}
public void anotherMethodInAirplane() {
this.brand();
super.brand();
}
}
public class Main {
public static void main(String[] args) {
Airplane airplane = new Airplane();
airplane.anotherMethodInAirplane();
}
}
如果你执行这个,你会看到 this.brand() 首先打印“This is an plane”,然后 super.brand() 打印“This is a vehicle”。
所以,
希望对你有帮助!如果您有任何后续问题,请继续。如果此答案对您有所帮助,如果您将此答案标记为“已接受”,我将不胜感激。祝你有美好的一天:)