简体   繁体   中英

Superclass using subclass version of method?

我可以看到子类如何继承超类方法,但是如果超类要使用该方法的子类版本怎么办?

In the superclass you then will need to define the method abstractly.

Example:

abstract protected void doSomething();

And then @Override this method in the subclass.

Now your superclass knows about this, and can call it.

Edit , this also requires the superclass to be abstract, as else you cannot have abstract methods on a class.

The general answer to your question is to have your superclass call an overridable method on itself. Here's an example:

Superclass

public class MyClass {

    // This method calls other (overridable) methods on itself
    public void run() {
            doSetup();
            doAction();
            doCleanup();
    }

    /** 
     * These three methods could be abstract if there's no default behavior
     * for the superclass to implement. In this example, these are concrete 
     * (not abstract) methods because there is a default behavior.
     */

    protected void doSetup() {
            System.out.println( "Superclass doSetup()" );
    }

    protected void doAction() {
            System.out.println( "Superclass doAction()" );
    }

    protected void doCleanup() {
            System.out.println( "Superclass doCleanup()" );
    }
}

Child class

public class MySubclass extends MyClass {

    /**
     * Override a couple of the superclass methods to provide a different 
     * implementation.
     */

    @Override
    protected void doSetup() {
            System.out.println( "MySubclass doSetup()" );
    }

    @Override
    protected void doCleanup() {
            System.out.println( "MySubclass doCleanup()" );
    }
}

Test Runner

public class Runner {

    public static void main( String... args ) {

            MyClass mySuperclass  = new MyClass();
            mySuperclass.run();  // calls the superclass method, gets the superclass
                                 // implementation because mySuperclass is an instance 
                                 // of MyClass

            MyClass child = new MySubclass();
            child.run();  // calls the superclass method, gets the child class 
                          // implementation of overridden methods because child is 
                          // an instance of MySubclass
    }
}

For an example of a design pattern where this approach is used, see the Template method pattern .

这是模板方法模式的典型用例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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