Can a Parent call Child Class methods?

前端 未结 3 1755
野的像风
野的像风 2020-12-02 17:23

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.

How can logic be implemen

相关标签:
3条回答
  • 2020-12-02 17:58

    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.

    0 讨论(0)
  • 2020-12-02 18:12

    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.

    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".

    0 讨论(0)
  • 2020-12-02 18:15

    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.

    0 讨论(0)
提交回复
热议问题