Code:
public class Foo {
public Foo() { System.out.println("constructor called"); }
static { System.out.println("static initializer called"); }
{ System.out.println("instance initializer called"); }
}
Execute :new Foo();
new Foo();
Output:static initializer called
instance initializer called
constructor called
instance initializer called
constructor called
--Varun
These are called as instance initializers. The code within these blocks are copied into every constructor by the compiler and are used to share common code across overloaded constructors.
ReplyDeletehttp://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
Exactly!! :-) Just came to know about this today!!
ReplyDeletethat is because static blocks are always called once when the class is loaded into the memory by JVM which is not the case with instance and constructor initializers.
ReplyDelete