Static block in Java not executed

前端 未结 5 1428
长情又很酷
长情又很酷 2020-11-28 03:32
class Test {
    public static void main(String arg[]) {    
        System.out.println("**MAIN METHOD");
        System.out.println(Mno.VAL); // SOP(9090)         


        
5条回答
  •  渐次进展
    2020-11-28 03:59

    1. Actually you have not extends that Mno class so when compilation start it will generate constant of variable VAL and when execution start when that variable is needed its load thats from memory. So its not required that your class reference so that static bock is not executed.

    2. if class A extends class Mno, the static block is included in class A if you do this then that static block is executed. For example..

      public class A extends Mno {
      
          public static void main(String arg[]){    
              System.out.println("**MAIN METHOD");
              System.out.println(Mno.VAL);//SOP(9090);
              System.out.println(Mno.VAL+100);//SOP(9190);
          }
      
      }
      
      class Mno {
          final static int VAL=9090;
          static {
              System.out.println("**STATIC BLOCK OF Mno\t:"+VAL);
          }
      }
      

提交回复
热议问题