Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 18, 2014 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeevprasanna/8493409 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8493409 to your computer and use it in GitHub Desktop.
Different ways of creating objects in Java
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");
}
}
}
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