What's wrong with overridable method calls in constructors?

后端 未结 7 1899
谎友^
谎友^ 2020-11-21 04:53

I have a Wicket page class that sets the page title depending on the result of an abstract method.

public abstract class BasicPage extends WebPage {

    pub         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 05:13

    Invoking an overridable method in the constructor allows subclasses to subvert the code, so you can't guarantee that it works anymore. That's why you get a warning.

    In your example, what happens if a subclass overrides getTitle() and returns null ?

    To "fix" this, you can use a factory method instead of a constructor, it's a common pattern of objects instanciation.

提交回复
热议问题