Created
January 18, 2014 17:17
-
-
Save rajeevprasanna/8493409 to your computer and use it in GitHub Desktop.
Different ways of creating objects in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package objectCreation; | |
public class TestObject implements Cloneable { | |
private String name = "DefaultTestName"; | |
public String getName() { | |
return name; | |
} | |
// By convention, classes that implement this interface should override | |
// Object.clone (which is protected) with a public method | |
// Refer : http://docs.oracle.com/javase/6/docs/api/java/lang/Cloneable.html | |
@Override | |
public Object clone() { | |
try { | |
return super.clone(); | |
} catch (CloneNotSupportedException e) { | |
throw new Error("Something impossible just happened"); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package objectCreation; | |
public class ObjectCreation { | |
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { | |
//1. Create object using new | |
TestObject object1 = new TestObject(); | |
System.out.println("Creating testObject instance using new keyword. name => "+ object1.getName()); | |
//2. Using class.forName | |
TestObject object2 = (TestObject)Class.forName("objectCreation.TestObject").newInstance(); | |
System.out.println("Object creatin using class.forName(). name => "+ object2.getName()); | |
//3.Using Clone | |
TestObject object3 = (TestObject) object2.clone(); | |
System.out.println("Created clone object. name => "+object3.getName()); | |
//4. Using serialization. We will discuss later in detail | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment