【问题标题】:Superclass using subclass version of method?超类使用方法的子类版本?
【发布时间】:2014-02-27 16:00:12
【问题描述】:

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

【问题讨论】:

  • 不能,不应该,也不应该。除非您的意思是通过多态性,这是自动的。我不知道你在问什么了。
  • 在超类中定义一个抽象方法,然后在超类的另一个方法中使用它。该行为将属于覆盖它的特定子类,例如:定义一个public abstract void init() 方法来加载配置。
  • 所以我想了解的是没有反向或反向继承吗?

标签: java class subclass superclass


【解决方案1】:

然后你需要在超类中抽象地定义方法。

例子:

abstract protected void doSomething();

然后在子类中@Override这个方法。

现在您的超类知道这一点,并且可以调用它。

编辑,这也要求超类是抽象的,否则你不能在一个类上拥有abstract 方法。

【讨论】:

  • 这样做需要将两个类同时编译在一起,并且永远更多。除非你真的知道自己在做什么,否则不推荐这种循环依赖。当需要修复anything时,必须先修复依赖链中的everything,然后any才能正常工作。
  • @alliteralmind 我可以想象,在几乎所有情况下,只要您使用这样的设计,这些类都应该在同一个包中,或者至少在同一个项目中。
  • 同意。在有限的情况下,这很有用。
【解决方案2】:

您的问题的一般答案是让您的超类对其自身调用一个可覆盖的方法。这是一个例子:

超类

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()" );
    }
}

儿童班

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()" );
    }
}

测试运行者

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
    }
}

有关使用此方法的设计模式示例,请参阅Template method pattern

【讨论】:

  • 你可能想在子类中添加显式的@Override注解。
【解决方案3】:

这是Template Method Pattern 的典型用例

【讨论】:

  • 我的意思是,如果您的超类需要调用特定的子类实现,则意味着它为进一步的步骤提供了一种框架,其实现只能在运行时知道。如果不是这种情况,并且您正试图从其超类调用子类方法,那么这是一个糟糕的 OOP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 2013-07-25
  • 2020-03-02
  • 2011-10-24
  • 1970-01-01
  • 2019-06-29
  • 2011-11-22
相关资源
最近更新 更多