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();
    }
}
发布了35 篇原创文章 · 获赞 0 · 访问量 2492

猜你喜欢

转载自blog.csdn.net/greywolf5/article/details/105261220