How to Create Object in Java
Rishi Gupta
SDET | Test Manager in Accenture | Selenium |Playwright| BDD |Cucumber| Java |Maven | Jenkins | Rest Assured API | JMeter | Agile
Java?provides five ways to create an object.
1.Using?new?Keyword
ClassName?object?=?new?ClassName();??
2.Using?clone()?method
The?clone()?method is the method of?Object?class. It creates a copy of an object and returns the same copy. The?JVM?creates a new object when the clone() method is invoked.
3.Using?newInstance()?method of the?Class?class
The?newInstance()?method of the Class class is also used to create an object. It calls the default constructor to create the object.?
?Syntax: protected?Object?clone()?throws?CloneNotSupportedException?
Example : ClassName?object?=?ClassName.class.newInstance();??
4.Using?newInstance()?method of the?Constructor?class
It is similar to the?newInstance()?method of the?Class?class. It is known as a reflective way to create objects.
Example: Constructor<Employee>?constructor?=?Employee.class.getConstructor();???
Employee?emp3?=?constructor.newInstance();??
5.Using?Deserialization
Deserialization?is the process of converting byte-stream to object.?
The JVM creates a new object when we serialize or deserialize an object.
The method?readObject()?of?ObjectInputStream?class is used to deserialize an object. It references objects out of a stream.
Syntax:
public?final?Object?readObject()?throws?IOException,ClassNotFoundException