What are all the different ways to create an object in Java?

Love and Share

Answer:  There are 5 different ways to create objects in java:

– Using new keyword . Almost 99% of objects are created in this keyword.

Accountant acn1 = new Accountant();


– Using Class.forName()

 

Accountant acn2 = (Accountant) Class.forName(“com.nxtechnp.Accountant”) .newInstance();

 


 

 –  Using clone()

Accountant acn4 = (Accountant) acn3.clone();


 

 – Using newInstance()

Constructor<Accountant> constructor = Accountant.class.getConstructor(); Accountant acn3= constructor.newInstance();


 – Using object deserialization

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj")); Accountant acn5= (Accountant) in.readObject();

 

Love and Share

Leave a Reply

Your email address will not be published. Required fields are marked *