Why is a subclass' static initializer not invoked when a static method declared in its superclass is invoked on the subclass?

前端 未结 7 1347
南方客
南方客 2021-02-02 13:16

Given the following classes:

public abstract class Super {
    protected static Object staticVar;

    protected static void staticMethod() {
        System.out.p         


        
7条回答
  •  一整个雨季
    2021-02-02 13:53

    When static block is executed Static Initializers

    A static initializer declared in a class is executed when the class is initialized

    when you call Sub.staticMethod(); that means class in not initialized.Your are just refernce

    When a class is initialized

    When a Class is initialized in Java After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

    1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.

    2) an static method of Class is invoked.

    3) an static field of Class is assigned.

    4) an static field of class is used which is not a constant variable.

    5) if Class is a top level class and an assert statement lexically nested within class is executed.

    When a class is loaded and initialized in JVM - Java

    that's why your getting null(default value of instance variable).

        public class Sub extends Super {
        static {
            staticVar = new Object();
        }
        public static void staticMethod() {
            Super.staticMethod();
        }
    }
    

    in this case class is initialize and you get hashcode of new object().If you do not override staticMethod() means your referring super class method and Sub class is not initialized.

提交回复
热议问题