Every user defined class is loaded into the memory whenever it is referred.
On the other hand, the system classes present in the java package are loaded when the JVM starts up.
The steps followed while loading a Java class are:
1) Check if the class has been already loaded by any of the parent
class-loaders. Since JVM has a hierarchy of class-loaders, particular
class could be loaded at any earlier point of time by using the System,
Classpath or User defined class loaders.
2) If the class is yet to be loaded then create static variables and
execute static code blocks. The execution order of static blocks is same
as the order in which they are defined.
3) If the class is to be loaded because it is referenced while creating
an instance of that class then all the super class constructors are
executed before executing this class's constructor. This is because
HotSpot places "super();" statement as the first line of each
constructor, but this can be changed by explicitly placing a class to
some other constructor with or without arguments.
The above statements can be verified by executing the following program:
public class Test {
static {
System.out.println("hi");
}
public Test() {
this(2);
System.out.println("Constructor 1");
}
public Test(int a) {
System.out.println("Constructor 2");
}
public static void main(String[] args) {
System.out.println("main");
Test t = new Test();
t.a();
}
static {
System.out.println("hi 2");
}
public void a() {
System.out.println("aa");
}
static {
System.out.println("hi 3");
}
}
Output:
hi
hi 2
hi 3
main
Constructor 2
No comments:
Post a Comment