0

As per this question, while I understand why it goes wrong, how can I effectively solve this while keeping my code DRY? I wouldn't want to copy and paste the contents in that function into the constructor.

Suppose I have the following

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

    void overridableFunction()
    { ... }
}

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

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

Ideally, I wish the execution flow of the Child constructor to be Parent() --> Parent.overridableFunction() --> Child.overridableFunction()

How can I achieve this without copying and pasting stuff around thus making the code WET?

Community
  • 1
  • 1
Rufus
  • 5,111
  • 4
  • 28
  • 45

2 Answers2

1

If you wish Parent's constructor to execute its own implementation of overridableFunction() and Child's constructor to execute its own implementation of overridableFunction(), what you are basically saying is you don't want Child's overridableFunction() to override Parent's overridableFunction() method.

You can give the two methods different names, or keep the names identical, but make Parent's method private, to avoid any overriding.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Wouldn't removing `overridableFunction();` from `Child` constructor result in `Parent` and `Child` each executing its own implementation of `overridableFunction()` ? – c0der Mar 23 '17 at 08:13
  • @c0der Based on what the OP wrote (`Ideally, I wish the execution...`), he wants both methods to be executed when creating an instance of the Child class. Therefore he doesn't want to remove it. – Eran Mar 23 '17 at 08:16
0

I am not sure why you want to do it, but this follows the execution flow you asked for :

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 ");
    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65