Java no name static method

久未见 提交于 2019-12-03 05:40:27

问题


What is this?

public class ABC {
   public ABC() {
         System.out.println("world");
   }
   static {
         System.out.println("hello");
   }
}

Will print: hello world

I don't really understand this, or what kind of method that static code is.


回答1:


It's called a "static initialisation block".

It runs when the class is first loaded; only once.

For example, a constructor will run each time the class is instantiated; the static block only runs once, when it's first loaded statically by the VM/Class loader.




回答2:


I think it's worth noting the static block will be run exactly once each time a classloader loads a class. This means if you have more than one classloader, the block can execute more than once.



来源:https://stackoverflow.com/questions/1836227/java-no-name-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!