Ques : How many ways create an Object In Java?
In interview asked how to create an object in java generally and everyone says
using the “new” operator to create an Object of a Class. But is it the only way to create an Object?
Simple answers is NO, then in how many ways we can create Object of a Class.
There are four different ways to create objects 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.
2. 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.
3. Using clone():
The clone() can be used to create a copy of an existing object.
4. Using Object Deserialization :
Object deserialization is nothing but creating an object from its serialized form.
In interview asked how to create an object in java generally and everyone says
using the “new” operator to create an Object of a Class. But is it the only way to create an Object?
Simple answers is NO, then in how many ways we can create Object of a Class.
- Using New keyword
- Class.forName()
- Using Clone()
- Using Deserilization
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 object = new Object();
|
2. 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 obj = (MyObject) class.forName("object").newInstance();
|
3. Using clone():
The clone() can be used to create a copy of an existing object.
MyObject obj = new MyObject();
MyObject object = (MyObject )obj.clone();
|
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream istream = new objectInputStream(some data);
MyObject object=(MyObject)
instream.readObject();
|
No comments:
Post a Comment