I have a couple of questions about instances of the class Class
1) Do I understand correctly that say for the class Dog there is only one instance of the class Class. In other words, given the following lines
Dog dog1 = new Dog();
Dog dog2 = new Dog();
Class dog1Class = dog1.getClass();
Class dog2Class = dog2.getClass();
Class dogClass = Dog.class;
there is only one instance of the class Class - Class<Dog>
.
If you compare these references with ==, you get that they are the same object.
The question exactly is, will getClass and static .class always return the same instance during one execution of a main method?
2) When exactly are these instances created?
will getClass and static .class always return the same instance
No, not exactly. dog.getClass()
method returns the runtime type of dog.
Consider the following classes:
class Animal { }
class Dog extends Animal { }
And then in main method:
Animal dog = new Dog();
System.out.println(dog.getClass()); // Prints class Dog
System.out.println(Animal.class); // Prints class Animal
When exactly are these instances created?
When the class is first loaded by JVM. From documentation of Class:
Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
For detailed study:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With