Different ways to create an Object in Java
In this post, we will discuss the different ways to create a new Object
Consider we have a class, say CustomClass and we are going to see different ways in which we can create a new object of CustomClass.
Consider we have a class, say CustomClass and we are going to see different ways in which we can create a new object of CustomClass.
- Using new keyword/the constructor:
new CustomClass();
- Clone
You already have an object and you using Cloning to create a copy of that object
CustomClass myObject = new CustomClass(); CustomClassobject = (CustomClass) myObject.clone();
- Class.forName:
The reflection API gives us the ability to create objects without calling the constructor. Spring and Hibernate use reflection to create objects.
Class.forname(CustomClass);
- Deserialization is another way of creating the object. First you serialize and then deserialize to get the object.
Comments