top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can we create an Object instance without using new in Java?

+1 vote
489 views
How can we create an Object instance without using new in Java?
posted Jun 11, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Using Class.forName()

If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

Using clone()

The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();

Using object deserialization

Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

Please refer this: Page

answer Jun 15, 2015 by Karthick.c
Thank you.
Very intersting tutorial.
I suggest also to check this tutorial:
http://how-to-program-in-java.com/2015/11/23/java-objects-for-beginners-java-objects-tutorial/
...