Reputation: 1325
I am confused about a subject and can not find it on the web.
As I understand it, when the program starts the class loader loads the .class
files and store them in the memory as objects with the type Class
.
My question is when we use:
Test test = new Test();
Is the new object created using .class
file, or using the Class
object already in the memory?
Upvotes: 6
Views: 370
Reputation: 1359
Once a class is loaded into a JVM, the same class will not be loaded again for same class loader. New instance will be created from class object in memory (for same class loader).
Steps at high level (copied from https://www.ibm.com/developerworks/java/tutorials/j-classloader/j-classloader.html)
If still don't have a class, throw a ClassNotFoundException.
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class c = findLoadedClass(name);
if (c == null) {
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClass0(name);
}
} catch (ClassNotFoundException e) {
// If still not found, then invoke findClass in order
// to find the class.
c = findClass(name);
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
Example all of following will print same hashCode and refers to same Test.class
Test test1 = new Test();
Test test2 = new Test();
System.out.println(test2.getClass().hashCode());
System.out.println(test1.getClass().hashCode());
System.out.println(Test.class.hashCode());
For more details http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html?page=1
Upvotes: 5
Reputation: 1019
A class (.class) gets loaded into the method area(1 Per JVM). This is also a logical part of the heap.
So in your case Test.class will be present in the method area when it is loaded thru main method or some other class as a dependency in the following structure :
Method Area stores the following data per loaded class :
When the new Test()
is encountered, a new instance of the Test class will be created in the heap that represents an Object of type Test.
The above post explains more clearly on the storage principle in JVM.
Upvotes: 1