Could someone explain what is the difference between Class loading and instantiating a Class. When we load a class with Static variable does it also get instantiated the same ti
A class is loaded when it is referenced (e.g. by Class.forName()
).
You instanciate an object by creating an instance, e.g.
Object o = new Object();
You can also instanciate an object by using reflection.
static
members of a class are instanciated when the class is loaded, e.g.
public class Sample {
private static int variable = 10;
}
When I now load the class (e.g. by Class.forName("Sample");
) Then the variable variable
is initialized with the value 10
.
If you are creating a new instance of a class and it is not loaded before the class will be loade before (atomatically). So the construct Class.forName()
is only needed under special circumstances (if the class is not known by compile time e.g.).