开发者

Prevent method call from using subclass's method

I have something that in principle resembles the following:

public class Generic {

    public Generic(){
        doStuff();
    }

    protected void doStuff(){
        System.out.println("Generic");
    }

}

public class Specific extends Generic {

    public Specific(){
        super();
    }

    protected void doStuff(){
        super.doStuff();
        System.out.println("Specific");
    }

}

The errors I'm getting indicate that although the method is being called from the superclass, it's calling the subclass's version of the method. In the above example, instantiating a new Specific would print out both "Generic" and "Specific", even though doStuff() was called by Generic's constructor.

Long story short, 开发者_JAVA百科I don't want that. There's some added functionality in the subclass's method that causes problems if it's called before the object is fully initialized. How can I, within the constructor of the superclass, force it to use its own version of the method, rather than the most specialized one?


I don't think you can have a function in Java that both A) can be overridden, and B) doesn't behave polymorphically when called. I would suggest you do something like this to simulate the behavior you're asking about:

public class Generic {

    public Generic(){
        doGenericStuff();
    }

    private final void doGenericStuff() {
        System.out.println("Generic");
    }

    protected doStuff(){
        doGenericStuff();
    }

}

public class Specific extends Generic {

    public Specific(){
        super();
    }

    protected doStuff(){
        super.doStuff();
        System.out.println("Specific");
    }

}


How about having a initialized boolean flag in your Specific class like this:

public class Specific extends Generic {
    boolean initialized = false;
    public Specific(){
        super();
        initialized = true;
    }

    @Override
    protected void doStuff(){
        super.doStuff();
        if (!initialized) return;
        System.out.println("Specific");
    }

    public static void main(String[] args) {
        @SuppressWarnings("unused")
        Specific specific = new Specific();
    }
}

This one just calls Generic's doStuff() method since flag initialized is false when parent class is getting constructed and child class is not fully constructed. I believe that was the main reason why didn't want Specific's overridden method to be invoked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜