【问题标题】:Keeping it DRY when constructor needs to call overridable method当构造函数需要调用可覆盖的方法时保持 DRY
【发布时间】:2017-03-23 07:51:30
【问题描述】:

根据this question,虽然我理解它为什么会出错,但如何在保持代码干燥的同时有效地解决这个问题?我不想将该函数中的内容复制并粘贴到构造函数中。

假设我有以下内容

class Parent
{
    Parent()
    {
        overridableFunction();
    }

    void overridableFunction()
    { ... }
}

class Child extends Parent
{
    Child()
    {
        super();
        overridableFunction()
    }

    void overridableFunction()
    { ... // overridden }
}

理想情况下,我希望Child 构造函数的执行流程是 Parent() --> Parent.overridableFunction() --> Child.overridableFunction()

如何在不复制和粘贴东西的情况下实现这一点,从而使代码变湿?

【问题讨论】:

    标签: java oop constructor


    【解决方案1】:

    如果您希望Parent 的构造函数执行它自己的overridableFunction() 实现,而Child 的构造函数执行它自己的overridableFunction() 实现,那么您基本上是在说您不希望@ 987654325@ 的overridableFunction() 覆盖ParentoverridableFunction() 方法。

    您可以为这两个方法指定不同的名称,或保持名称相同,但将Parent 的方法设为私有,以避免任何覆盖。

    【讨论】:

    • 不会从Child 构造函数中删除overridableFunction(); 导致ParentChild 各自执行自己的overridableFunction() 实现?
    • @c0der 根据 OP 所写的内容 (Ideally, I wish the execution...),他希望在创建 Child 类的实例时执行这两种方法。因此他不想删除它。
    【解决方案2】:

    我不确定您为什么要这样做,但这遵循您要求的执行流程:

    class Parent
    {
        Parent()
        {
            overridableFunction();
        }
    
        void overridableFunction()
        { System.out.println("Parent implementation "); }
    
        public static void main(String[] args) {
             new Child();
        }
    }
    
    class Child extends Parent
    {
        Child()
        {
            super();
            //remove overridableFunction();
        }
    
        @Override
        void overridableFunction()
        {
            super.overridableFunction();
            System.out.println("Child implementation ");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2012-10-05
      • 2011-03-25
      • 2014-01-18
      相关资源
      最近更新 更多