java 当派生类中重写该方法时,如何使用派生类 Object 调用基类方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6066860/
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
How to call base class method with derived class Object when that method overridden in derived class?
提问by srikanth104
class A
{
public void m1()
{
System.out.println("hi-base class");
}
}
class B extends A
{
public void m1()
{
System.out.println("hi-derived ");
}
public static void main(String args[])
{
B b1=new B();
}
}
In this i want to invoke base class m1 method by using Derived class object without using the super
在此我想通过使用派生类对象而不使用 super 来调用基类 m1 方法
回答by dlev
You would need to construct an object of type A. You have overridden method m1 in the derived class, and so any calls to m1 on an object that was created as a B will have the B version of m1 invoked. Without using super
, there's no way to instruct the compiler to make the non-virtual call to the base-class version.
您将需要构造一个类型为 A 的对象。您在派生类中重写了方法 m1,因此在创建为 B 的对象上对 m1 的任何调用都将调用 m1 的 B 版本。如果不使用super
,就无法指示编译器对基类版本进行非虚拟调用。
回答by pickypg
Are you just looking for super.m1();
? This will invoke the immediate parent's method.
你只是在寻找super.m1();
吗?这将调用直接父级的方法。
However, you cannot instantiate an object of type B
from outside of B
and use this.
但是,您不能B
从外部实例化类型的对象B
并使用 this。
You cannot do:
你不能这样做:
B value = new B();
value.super.m1(); // call A's implementation
However, you could do this within B:
但是,您可以在 B 中执行此操作:
@Override
public void m1()
{
System.out.println("hi from B");
super.m1();
}
public void useAM1()
{
super.m1();
}
Of course, when you start to provide workarounds to get at functionality from A
, then it sounds like you are abusing inheritance, or at leastshould have used an instance of A
to begin with.
当然,当您开始提供变通方法以从 获取功能时A
,听起来您是在滥用继承,或者至少应该使用 的实例A
开始。
Interestingly, in C++ you could do this: value->A::m1();
. Fortunately, there is no equivalent in Java.
有趣的是,在C ++中,你可以这样做:value->A::m1();
。幸运的是,Java 中没有等价物。
回答by kuriouscoder
In short you cannot do it -- virtual dispatching would delegate the call to the referred.
简而言之,您不能这样做——虚拟调度会将调用委托给被引用的对象。