List all possible/different ways to create a Java object
The ways I know and have tried so far:
1. Using new keyword
This is the most common way to create an object in java. Most of the time, Java objects are created in this way.
MyTestObject obj = new MyTestObject();
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.
MyTestObject obj = (MyTestObject) Class.forName(“sing.test.MyTestClass”).newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyTestObject anotherObj = new MyTestObject();
MyTestObject obj = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyTestObject object = (MyTestObject) inStream.readObject();
About this entry
You’re currently reading “List all possible/different ways to create a Java object,” an entry on Singaram's Tech Musings
- Published:
- July 3, 2011 / 1:47 PM
- Category:
- Coding tips, Java

No comments yet
Jump to comment form | comment rss [?] | trackback uri [?]