Monday, 25 April 2016

How many ways to create an object ?


1. Using new keyword
MyClass object = new MyClass();

2. Using clone()
It creates a copy of an existing object.
MyClass secondObject  = object.clone();

3. Using Class.forName()
If we know the name of the class and it has a public default constructor we can create an object in this way.
MyObject object = 
    (MyObject) Class.forName("genius.MyObject").newInstance();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inputStream = new ObjectInputStream(xyzStream);
MyClass object = (MyClass) inputStream.readObject();

No comments:

Post a Comment

Note: only a member of this blog may post a comment.