在Java中,如何从派生类中的重写方法调用基类的方法?

Cre*_*ine 130 java methods polymorphism inheritance

我有两个Java类:B,它扩展了另一个类A,如下所示:

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public void myMethod() { /* Another code */ }
}
Run Code Online (Sandbox Code Playgroud)

我想打电话A.myMethod()B.myMethod().我来自C++世界,我不知道如何在Java中做这个基本的事情.

unw*_*ind 138

您正在寻找的关键字是super.例如,请参阅本指南.

  • 看起来在C++中你可以调用一个特定的祖先方法,但不是java,你可以把它传递给链...... (3认同)

Rob*_*bin 127

只需使用super调用它.

public void myMethod()
{
    // B stuff
    super.myMethod();
    // B stuff
}
Run Code Online (Sandbox Code Playgroud)


小智 20

答案如下:

super.Mymethod();
super();                // calls base class Superclass constructor.
super(parameter list);          // calls base class parameterized constructor.
super.method();         // calls base class method.
Run Code Online (Sandbox Code Playgroud)


小智 18

super.MyMethod()应该在里面叫MyMethod()class B.所以它应该如下

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public void myMethod() { 
        super.MyMethod();
        /* Another code */ 
    }
}
Run Code Online (Sandbox Code Playgroud)


Eli*_*lie 8

调用super.myMethod();


小智 8

我很确定你可以使用Java Reflection机制来完成它.它不像使用超级那样简单,但它会给你更多的力量.

class A
{
    public void myMethod()
    { /* ... */ }
}

class B extends A
{
    public void myMethod()
    {
        super.myMethod(); // calling parent method
    }
}
Run Code Online (Sandbox Code Playgroud)