如何在所有子构造函数中自动包含父方法的执行? [英] How to automatically include the execution of a parent's method in all child constructors?

查看:136
本文介绍了如何在所有子构造函数中自动包含父方法的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类( Parent ),它有一个抽象方法( doSetup )和一个成员方法它调用 doSetup 方法。我需要的是在构建时,子类(其实现 Parent )应该自动调用 doSetup 方法,而不管孩子类可能有很多构造函数。有没有Java机制或设计模式可以帮助我解决这个问题?

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


推荐答案

好的IDE可能会警告不要在构造函数中使用可覆盖的方法。

A good IDE probably will warn against using overridable methods in the constructor.

原因可以用下面的代码来证明,这可能是令人惊讶的结果。

The reason can be demonstrated with the following code that has maybe surprising results.

class Base {
    Base() {
        init();
    }

    protected void init() {
    }
}
class Child extends base {
    String a = "a";
    String b;
    String c = "c";
    String d;

    public Child() {
        // 1. Fields are nulled
        // 2. super() called
        // 2.1. init() called
        // 3. Field initialisations done (a, c)
        // 4. Rest of constructor:
        System.out.printf("EndConstr a: %s, b: %s, c: %s%n", a, b, c);
    }

    @Overridable
    protected void init() {
        System.out.printf("Init a: %s, b: %s, c: %s%n", a, b, c);
        c = "cc";
        d = "dd";
    }
}






控制行为的解决方案是提供一种最终的不可覆盖的方法,它以指定的方式调用可覆盖的受保护方法:


A solution to control behavior would be to offer one final non-overridable method that calls an overridable protected method in a specified way:

class Base {
    public final void f() {
        X x = ...;
        onF(x);
    }
    protected /*abstract*/ void onF(X x) {
    }
}
class Child extends Base {
    @Overridable
    protected void onF(X x) {
        ...
    }
}

这篇关于如何在所有子构造函数中自动包含父方法的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆