6

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?

10

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 initializer(s) for a class fire the first time the class is loaded (and before anything else). If you have an explicit static intializer you can use it to perform a global initialization if need be.

2

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.

  • ya why use a classloader rather than creating a instance of the class ..... – prasonscala Mar 1 '11 at 6:01
  • 2
    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
2

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.

  • 1
    Please do not try to add unnecessary (and potentially spammy) links to your answers. – ChrisF Oct 23 '12 at 7:53
1

Instantiating a class is when you create an instance of that class at runtime. Though I think what you're referring to could be class initialization? Just in case, class initialization occurs when any of the following happens:

1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.

2) a static method of Class is invoked.

3) a static field of Class is assigned.

4) a static field of class is used which is not a constant variable.

5) if Class is a top level class and an assert statement lexically nested within class is executed.

http://javarevisited.blogspot.com/2012/07/when-class-loading-initialization-java-example.html

Class loading is when the JVM pulls the class from its package and loads it into the runtime environment to be used at runtime. The class loader is responsible for this process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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