Being Java developers, we usually create lots of objects daily, but we always use dependency management systems e.g. Spring to create these objects. However, there are more ways to create objects, which we will study in this article.
There are five total ways to create objects in Java, which are explained below with their examples followed by bytecode of the line which is creating the object.
Using the new keyword
The constructor gets called
Using newInstance() method of Class class
The constructor gets called
Using newInstance() method of Constructor class
The constructor gets called
Using clone() method
No constructor call
Using deserialization
No constructor call
If you will execute program given in the end, you will see method 1, 2, 3 uses the constructor to create the object while 4, 5 doesn’t call the constructor to create the object.
It is the most common and regular way to create an object and a very simple one also. By using this method we can call whichever constructor we want to call (no-arg constructor as well as parameterized).
Employee emp1 = new Employee();
0: new #19 // class org/programming/mitra/exercises/Employee
3: dup
4: invokespecial #21 // Method org/programming/mitra/exercises/Employee.“”:()V
#### **2\. Using newInstance() method of Class class **
We can also use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor to create the object.
We can create an object by newInstance() in the following way:
Employee emp2 = (Employee) Class.forName(“org.programming.mitra.exercises.Employee”).newInstance();
Or
Employee emp2 = Employee.class.newInstance();
51: invokevirtual #70 // Method java/lang/Class.newInstance:()Ljava/lang/Object;
```
#java #core java #reflection api