Tuesday, July 21, 2015

Different ways to create an object in JAVA

There are 4 different ways to create an object in JAVA.


1) Using new keyword - This is the most common way to create an object in JAVA.
     Almost 99% of objects are created in this way.

     MyObject obj = new MyObject();


2) Using Class.forName() - Also known as dynamic/runtime object creation.

     MyObject obj = (MyObject) Class.forName("MyObject").newInstance();


3) Using clone() - Create a copy of an existing object.

     MyObject anotherObj = new MyObject();
     MyObject obj = anotherObj.clone();


4) Using object Deserialization - Create object from its serialized form.

    ObjectInputStream inStream = new  ObjectInputStream(aInputStream);
    MyObject obj = (MyObject) inStream.readObject();

 

No comments:

Post a Comment

Home