【问题标题】:Simple question about Inheritance in Java关于Java继承的简单问题
【发布时间】:2021-02-15 11:38:41
【问题描述】:

我有一个关于继承的问题。 如果我想在子类中调用父类的方法,我应该使用super.method() 还是this.method()?在我正在编程的程序中,它们都可以工作,所以我同时使用它们,但我并不认为这是正确的方法。

例如,假设我有一个名为“Vehicle”的类和另一个我们称之为“Airplane”的类。假设我在 Vehicle 中有一个 brand() 方法。我应该使用this.brand() 还是super.brand()

【问题讨论】:

  • 如果您的类中没有覆盖该方法,您可以同时使用 this.brand(与 brand() 相同)和 super.brand()。如果重写它,this.brand() 指向新方法,而 super.brand() 调用原始方法。

标签: java object inheritance


【解决方案1】:

考虑一下这段代码sn-p,

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() 首先打印“这是一架飞机”,然后 super.brand() 打印“这是一辆汽车”。

所以,

  1. 如果调用 super.someMethod(),它将始终调用超类中的方法。
  2. 如果您调用 this.someMethod() 并且 someMethod() 已被您的子类(本例中为 Airplane)覆盖,那么它将被调用。
  3. 但是,如果 someMethod() 在您的子类中没有被覆盖,那么 someMethod() 的超类实现将默认执行

希望对您有所帮助!如果您有任何后续问题,请继续。如果此答案对您有所帮助,如果您将此答案标记为“已接受”,我将不胜感激。祝你有美好的一天:)

【讨论】:

  • 感谢您的回答! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2011-03-28
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
相关资源
最近更新 更多