java - Static block is not getting executed in case of anonymous objects -
why doesn't static block in class executed when don't create reference variable object (anonymous) of class?
for example, allow consider simple class:
public class staticdemo { private static int x; public static void display(){ system.out.println("static method: x = "+x); } static { system.out.println("static block within class"); } public staticdemo(){ system.out.println("object created."); } }
another class using it:
public class usestaticdemo { public static void main(string[] args) { staticdemo obj = new staticdemo(); obj.display(); system.out.println("------------"); new staticdemo().display(); } }
output:
static block within class object created. static method: x = 0 ------------ object created. static method: x = 0
a static
initializer block runs once, when class loaded , initialized.
also, static
methods have absolutely no relation instances. doing
new staticdemo().display();
is pointless , unclear.
java static
No comments:
Post a Comment