Java 父类可以调用子类方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1387207/
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
Can a Parent call Child Class methods?
提问by Kevin Boyd
Referring here
参考这里
A is a precompiled Java class (I also have the source file)
B is a Java class that I am authoring
B extends A.
A 是预编译的 Java 类(我也有源文件) B 是我正在创作的 Java 类
B 扩展 A。
How can logic be implemented such that A can call the methods that B has.
The following are the conditions:
如何实现逻辑,使 A 可以调用 B 拥有的方法。
以下是条件:
- I don't want to touch A(only as a last option though that is if no other solution exists).
- I don't want to use reflection.
- 我不想触摸 A(仅作为最后一个选项,但如果不存在其他解决方案)。
- 我不想使用反射。
As stated, if needed I could modify A. What could be the possible solution either way?
如上所述,如果需要,我可以修改 A. 两种可能的解决方案是什么?
采纳答案by Alex Martelli
Class A
should define the methods it's going to call (probably as abstract ones, and A should be an abstract class, per Paul Haahr's excellent guide); B
can (in fact to be concrete MUST, if the method are abstract) override those methods. Now, calls to those methods from other methods in A
, when happening in an instance of class B, go to B's overrides.
类A
应该定义它要调用的方法(可能是抽象的,A 应该是一个抽象类,根据 Paul Haahr 的优秀指南);B
可以(实际上是具体的必须,如果方法是抽象的)覆盖这些方法。现在,从 中的其他方法调用这些方法A
,当在类 B 的实例中发生时,转到 B 的覆盖。
The overall design pattern is known as Template Method; the methods to be overridden are often called "hook methods", and the method performing the calls, the "organizing method".
整体设计模式称为模板方法;要覆盖的方法通常称为“挂钩方法”,执行调用的方法称为“组织方法”。
回答by San Jacinto
I would be rather hesitant to do this. Please correct me if I am wrong and then I will delete, but it sounds like you want to maintain an A object along with a B object. If they indeed are not the same object, the "tying together" (that's a scientific term) you'll have to do would be pretty ugly.
我会很犹豫要不要这样做。如果我错了,请纠正我,然后我将删除,但听起来您想同时维护一个 A 对象和一个 B 对象。如果它们确实不是同一个对象,那么您必须做的“捆绑在一起”(这是一个科学术语)将非常难看。
回答by Timmmm
Yes it seems that if you override the super/base-classes's functions, calls to those functions inthe base class will go to the child/derived class. Seems like a bad design in my opinion, but there you go.
是的,它看来,如果你重写超/基类的函数,这些函数的调用在基类中必去的孩子/派生类。在我看来,这似乎是一个糟糕的设计,但你去了。
class Base
{
public void foo()
{
doStuff();
}
public void doStuff()
{
print("base");
}
}
class Derived extends Base
{
@Override
public void doStuff()
{
print("derived");
}
}
new Derived().foo(); // Prints "derived".
Obviously all of Derived
's methods have to be already defined in Base
, but to do it otherwise (without introspection) would be logically impossible.
显然, 的所有Derived
方法都必须已经在 中定义Base
,但否则(没有自省)在逻辑上是不可能的。