小编Str*_*nst的帖子

Java-强制子类在构造函数之后调用超级方法

我希望一堆子类在完成如下构造函数后调用一个超级方法:

public abstract class Superclass {

    ...

    public Superclass(...) {
        ...    // do stuff before initializing subclass
    }

    protected void dispatch() {     //method to be called directly after creating an object
        doStuff();
        ...
    }

    public abstract void doStuff();
}

public class Subclass extends Superclass {

    ...

    public Subclass(...) {
        super(...);     //has to be the first line
        ...             //assign variables etc.
        dispatch();     //has to be called after variables are assigned etc.
    }

    public void doStuff() {
        //do stuff with assigned variables …
Run Code Online (Sandbox Code Playgroud)

java inheritance constructor

1
推荐指数
2
解决办法
1000
查看次数

标签 统计

constructor ×1

inheritance ×1

java ×1