开发者

Java no name static method

开发者 https://www.devze.com 2022-12-13 06:12 出处:网络
What is this? public class ABC { public ABC() { System.out.println(\"world\"); } static { System.out.println(\"hello\");

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号