"Do not call overridable methods in constructors" — what about this()?

I can’t find any other questions that touch on this. Suppose I have a class with multiple constructors (it isn’t mine, so I can’t use a Builder instead):

public class TextField {
    public TextField() {
        clear();
    }

    public TextField(String caption) {
        this();
        setCaption(caption);
    }
}

This seems to violate the golden rule that you should never call overridable methods in constructors. I’ve seen people call these “telescoping constructors”. Why is this pattern everywhere I look, in constructors? Does it simply predate the rule?

If I want to make a subclass that does something “extra” in the initialization, do I just override the zero-argument constructor and let the other one handle it indirectly? I.e.:

public class ImmediateTextField extends TextField {
    public ImmediateTextField() {
        super();
        setImmediate(true);
    }

    public ImmediateTextField(final String caption) {
        // Will call `this()` implicitly, and thus also `setImmediate(true)`!
        super(caption);
    }
}

It feels really weird — like I’m being forced to violate the rule, because a package I’m using does so! What’s the best practice here?


Source: oop

Leave a Reply