简体   繁体   English

Parent可以调用Child Class方法吗?

[英]Can a Parent call Child Class methods?

Referring here 在这里提到

A is a precompiled Java class (I also have the source file) B is a Java class that I am authoring A是预编译的Java类(我也有源文件)B是我正在创作的Java类
B extends A. B延伸A.

How can logic be implemented such that A can call the methods that B has. 如何实现逻辑,以便A可以调用B具有的方法。
The following are the conditions: 以下是条件:

  • I don't want to touch A(only as a last option though that is if no other solution exists). 我不想触摸A(仅作为最后一个选项,但如果不存在其他解决方案)。
  • I don't want to use reflection. 我不想使用反射。

As stated, if needed I could modify A. What could be the possible solution either way? 如上所述,如果需要,我可以修改A.无论哪种方式,可能的解决方案是什么?

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 ); A应该定义它要调用的方法(可能是抽象的,而A应该是一个抽象类,每保罗Haahr的优秀指南 ); B can (in fact to be concrete MUST, if the method are abstract) override those methods. B可以(实际上是具体的,如果方法是抽象的)覆盖那些方法。 Now, calls to those methods from other methods in A , when happening in an instance of class B, go to B's overrides. 现在,当在B类实例中发生时,从A其他方法调用这些方法转到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". 要重写的方法通常称为“钩子方法”,执行调用的方法称为“组织方法”。

Yes it seems that if you override the super/base-classes's functions, calls to those functions in the 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定义,但是否则(没有内省)这样做在逻辑上是不可能的。

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. 如果我错了请纠正我然后我会删除,但听起来你想要保持A对象和B对象。 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. 如果它们确实不是同一个对象,那么你必须做的“捆绑在一起”(这是一个科学术语)会非常难看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM