Java如何调用祖父母的方法?
假设我有 3 个类 A
、B
和 C
,每个类都扩展了前一个类。
如果 B
也实现了 myMethod
,如何从 C.myMethod()
调用 A.myMethod()
中的代码>?
class A
{
public void myMethod()
{
// some stuff for A
}
}
class B extends A
{
public void myMethod()
{
// some stuff for B
//and than calling A stuff
super.myMethod();
}
}
class C extends B
{
public void myMethod()
{
// some stuff for C
// i don't need stuff from b, but i need call stuff from A
// something like: super.super.myMethod(); ?? how to call A.myMethod(); ??
}
}
Possible Duplicate:
Why is super.super.method(); not allowed in Java?
Let's assume I have 3 classes A
, B
and C
, each one extending the previous one.
How do I call the code in A.myMethod()
from C.myMethod()
if B
also implements myMethod
?
class A
{
public void myMethod()
{
// some stuff for A
}
}
class B extends A
{
public void myMethod()
{
// some stuff for B
//and than calling A stuff
super.myMethod();
}
}
class C extends B
{
public void myMethod()
{
// some stuff for C
// i don't need stuff from b, but i need call stuff from A
// something like: super.super.myMethod(); ?? how to call A.myMethod(); ??
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能,也不应该。
这是糟糕设计的标志。重命名方法或在另一个方法或实用程序类中包含所需的通用功能。
You can't, and you shouldn't.
This is a sign of bad design. Either rename a method or include the required common functionality in another method or an utility class.
我不确定你可以。 Java 默认将所有方法设为虚拟方法。这意味着最简单的解决方案将不起作用:声明一个
A
类型的变量,将您的C
实例分配给它并调用myMethod
将导致在C.myMethod
中被调用。您可以尝试反映类型 A 并直接调用其方法。看看这种情况下会发生什么会很有趣,但如果虚拟调度不会发生,我会感到惊讶......
I'm not sure you can. Java makes all methods virtual by default. This means that the most simple solution will not work: Declare a variable of type
A
, assign yourC
instance to it and callmyMethod
will result inC.myMethod
being called.You could try to reflect type
A
and invoke its methods directly. It would be interesting to see what happens in this case, but I'd be surprised if the virtual dispatch wouldn't happen...你不能。这是故意的。
类
B
为子类提供接口(如概念中所示,而不是Java 关键字)。它选择不直接访问A.myMethod
的功能。如果您需要B
提供该功能,请使用不同的方法(不同的名称,使其受保护
)。然而,“更喜欢组合而不是继承”可能更好。You can't. This is deliberate.
Class
B
provides an interface (as in the concept, not the Java keyword) to subclasses. It has elected not to give direct access to the functionality ofA.myMethod
. If you requireB
to provide that functionality, then use a different method for it (different name, make itprotected
). However, it is probably better to "prefer composition over inheritance".