在 Java 中,如何从派生类中的覆盖方法调用基类的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/268929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, how do I call a base class's method from the overriding method in a derived class?
提问by Creasixtine
I have two Java classes: B, which extends another class A, as follows :
我有两个 Java 类:B,它扩展了另一个类 A,如下所示:
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
I would like to call the A.myMethod()
from B.myMethod()
. I am coming from the C++ world, and I don't know how to do this basic thing in Java.
我想A.myMethod()
从B.myMethod()
. 我来自C++ 世界,我不知道如何在 Java 中做这个基本的事情。
采纳答案by unwind
The keyword you're looking for is super
. See this guide, for instance.
您要查找的关键字是super
。例如,请参阅本指南。
回答by Elie
call super.myMethod();
调用 super.myMethod();
回答by Robin
Just call it using super.
只需使用 super 调用它。
public void myMethod()
{
// B stuff
super.myMethod();
// B stuff
}
回答by Steve K
super.MyMethod()
should be called inside the MyMethod()
of the class B
. So it should be as follows
super.MyMethod()
应该在里面叫MyMethod()
的class B
。所以应该如下
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() {
super.MyMethod();
/* Another code */
}
}
回答by kinshuk4
super.baseMethod(params);
call the base methods with superkeyword and pass the respective params.
使用super关键字调用基本方法并传递相应的参数。
回答by Yograj kingaonkar
Answer is as follows:
答案如下:
super.Mymethod();
super(); // calls base class Superclass constructor.
super(parameter list); // calls base class parameterized constructor.
super.method(); // calls base class method.
回答by umanathan
// Using super keyword access parent class variable
class test {
int is,xs;
test(int i,int x) {
is=i;
xs=x;
System.out.println("super class:");
}
}
class demo extends test {
int z;
demo(int i,int x,int y) {
super(i,x);
z=y;
System.out.println("re:"+is);
System.out.println("re:"+xs);
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(4,5,6);
}
}
回答by umanathan
class test
{
void message()
{
System.out.println("super class");
}
}
class demo extends test
{
int z;
demo(int y)
{
super.message();
z=y;
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(6);
}
}
回答by Gracjan Nawrot
I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.
我很确定您可以使用 Java 反射机制来做到这一点。它不像使用 super 那样简单,但它会给你更多的力量。
class A
{
public void myMethod()
{ /* ... */ }
}
class B extends A
{
public void myMethod()
{
super.myMethod(); // calling parent method
}
}