Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In Java world, there are some scenarios where I see developers used to load the class rather than instantiation. What is the difference between instantiating and loading a class?

share|improve this question
3  
I think this would have suited better on StackOverflow. –  gablin Mar 1 '11 at 11:44
add comment

3 Answers

up vote 7 down vote accepted

In order for a class to be instantiated it has to be loaded by the classloader...in many cases this is the first time the class has been just-in-time compiled. If you access a static variable on a class, it has to be loaded. If you want to reflect on a class it has to be loaded. There are many circumstances where you might just load a class rather than instantiate.

Also the static constructor for a class fires the first time the class is loaded (and before anything else). If you have an explicit static constructor you can use it to perform a global initialization if need be.

share|improve this answer
add comment

I am not sure if this is what you mean, but a classloader actually locates the definition for a class and makes it available for use by the JVM. Then, you can instantiate an instance of it.

share|improve this answer
    
ya why use a classloader rather than creating a instance of the class ..... –  prasonscala Mar 1 '11 at 6:01
1  
You must have a class loaded before you can instantiate it. They are not alternatives to each other. What examples are you seeing where this is the case? –  Matt H Mar 1 '11 at 6:03
add comment

Generally, "class loading" refers to loading, and initializing the class definitions - meaning loading the bytecode from the class file, creating the Class class, running the static initializers, etc.

Once a class is loaded, and initialized, then it would be possible to instantiate an instance of the class -- ie. create an object of that class type.

share|improve this answer
1  
Please do not try to add unnecessary (and potentially spammy) links to your answers. –  ChrisF Oct 23 '12 at 7:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.