Saturday, December 27, 2014

Multiple way to create java object

My title
There are four ways to create object in java-

1.    Using new keyword, maximum time we use it.
       MyObj myObj = new MyObj();

2.  Using Class.forName("ClassName")
     If we already know the class name and that contain a default constructor then only we can create
     the object in this way.
     MyObj myObj = (MyObj)Class.forName("MyObj").newInstance();

3. Using clone()
     The clone() can be used to create a copy of an existing object.
     MyObject myObj= new MyObject();
     MyObject object = anotherObject.clone();

4. Using Deserilization 
 Object deserialization is nothing but creating an object from its serialized form.
 ObjectInputStream inStream = new ObjectInputStream(anInputStream );
 MyObject myObj=  (MyObject) inStream.readObject();

No comments:

Post a Comment