What Are The Different Ways To create An Object in Java With Example?

What Are The Different Ways To create An Object in Java With Example?

As a Java developer we should know different ways to create object in java.There are Number of ways To create Object In java .Let's See One by one.

1.using new Keyword

This is normal way of creating object in java.mostly all developers know this.


Java2study object = new Java2study();
2.Class.newInstance()

Class.newInstance() method is reflective method for creating instances of classes. Class.newInstance() can only invoke the no-argument constructor. Below code is to create object of class by using Class.newIstace()


Java2study object = (Java2study)Class.forName(“com.java2study.practice.Java2Study”).newIstance();
3.clone() method

when you call clone() method on any object ,clone() method will create copy of object.check the below code.


Laptop objec = new Laptop();
Laptop2 objectcopy = (Laptop2)obect.clone();
4.using deserialization

When we Deserialize Object Jvm will create the instance which meanse we are creatig object from serialization.


ObjectInputStream ois = new ObjectInputStream(“abc.txt”);
Laptop laptop = (Laptop)ois.readObject();
-->