Domanda di colloquio di Surya Informatics

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

Risposta di colloquio

Anonimo

5 set 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(); }