问题描述
我们假设我有3个班级 A
, B
和 C
,每一个都扩展了前一个。
Let's assume I have 3 classes A
, B
and C
, each one extending the previous one.
如何从 C.myMethod()调用
如果 A.myMethod()
中的代码 B
还实现 myMethod
?
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(); ??
}
}
推荐答案
你不能。这是故意的。
类 B
为子类提供一个接口(如概念中,而不是Java关键字) 。它选择不直接访问 A.myMethod
的功能。如果您需要 B
来提供该功能,请使用不同的方法(不同的名称,使其 protected
) 。但是,更喜欢构图而不是继承可能更好。
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 of A.myMethod
. If you require B
to provide that functionality, then use a different method for it (different name, make it protected
). However, it is probably better to "prefer composition over inheritance".
这篇关于Java如何调用盛大父母的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!