Question d’entretien chez Surya Informatics

When designing an abstract class, why should you avoid calling abstract methods inside its constructor?

Réponse à la question d'entretien

Utilisateur anonyme

5 sept. 2017

This is a problem of initialization order. The subclass constructor will not have had a chance to run yet and there is no way to force it to run it before the parent class. Consider the following example class: public abstract class Widget { private final int cachedWidth; private final int cachedHeight; public Widget() { this.cachedWidth = width(); this.cachedHeight = height(); } protected abstract int width(); protected abstract int height(); }