Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instances of the class Class

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?

like image 814
Average Joe Avatar asked Sep 01 '13 15:09

Average Joe


1 Answers

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:

  • JVM Specification - Loading, Linking, and Initializing
  • JLS - Loading of Classes and Interfaces
like image 173
Rohit Jain Avatar answered Oct 11 '22 08:10

Rohit Jain