Monday, 20 July 2015

Create an Object

Using new keyword:
Almost 99% of objects are created in this way.
MyClass myClass = new MyClass();

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.
1st way to create object using reflection.
MyClass usingreflection= (MyClass)Class.forName("com.create.MyClass").newInstance();

2nd  way to create object using reflection.

MyClass usingRefl2 = MyClass.class.newInstance();

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

Using object deserialization:
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream);
MyClass object = (MyClass) inStream.readObject();

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...