lundi 11 avril 2016

How to automatically include the execution of a parent's method in all child constructors?

I have an abstract class (Parent) which has an abstract method (doSetup), and a member method which calls the doSetup method. What I need is the child class (which implements Parent) at construction should automatically call the doSetup method, regardless of however many constructors the child class might have. Is there a Java mechanism or a design pattern which could help me solve this?

public abstract class Parent {
  abstract protected void sayHi();
  protected void doSetup() {
    sayHi();
  }
}

public class Child1 extends Parent {
  @Override
  protected void sayHi() {
    System.out.println("hi");
  }
  public Child1() {
    // Construction needs to automatically include exec of doSetup()
  }
  public Child1(String string) {
    // Construction needs to automatically include exec of doSetup()
    System.out.println("another constructor");
  }
}

Aucun commentaire:

Enregistrer un commentaire