Behavior of static blocks with inheritance

后端 未结 5 856
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 20:13

I am trying to use static blocks like this:

I have a base class called Base.java

public class Base {

    static public int myVar;

}
         


        
5条回答
  •  再見小時候
    2020-12-02 20:59

    When we do

    class Base {
    
        public static int myVar = 0;
        static {
            System.out.println("Base");
        }
    }
    
    class Derived extends Base {
    
        static {
            System.out.println("Derived");
            Base.myVar = 9;
    
        }
    }
    
    public class StaticBlock {
    
        public static void main(String[] args) {
    
            System.out.println(Base.myVar);
            System.out.println(Derived.myVar);
        }
    }
    

    The Output will be Base 0 0

    That means derived class's static block not executing..!!

提交回复
热议问题