Item19:Design and document for inheritance or else prohibit it

下面的代碼的運行結果:

null
2020-04-01T23:56:06.132Z

實例化子類,子類會在調用自己的構造器前,先調用父類的構造器。如果父類構造器調用的方法被子類覆蓋,並且這個overriding父類方法的方法裏,有使用需要subclass constructor 初始化的對象(such as “Instant” in this case ), 那麼父類constructor在調用被覆蓋的subclass method時,這個方法裏使用的對象還沒有initialized(initialized by subclass constructor )

class Subclass extends Super{

    private final Instant instant;

    Subclass(){
        instant = Instant.now();
    }

    public void overridable(){
        System.out.println(instant);
    }

    public static void main(String[] args) {
        Subclass subclass = new Subclass();
        subclass.overridable();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章