Different ways of creating Objects in Java

Different ways of creating Objects
  • Using new operator.
  • Using Class.forName() and newInstance().
  • Using Factory Methods
  • Using Object cloning
  • Using Object deserialization
Object Creation By Different Methods
public class ObjectCreation {
 
  public static void main(String args[])throws Exception{

    ObjectCreation objecByNewKeyword = createObjecByNewKeyword();
    ObjectCreation objecByClassForName = createObjecByClassForName();
    ObjectCreation objecByCloning = (ObjectCreation)createObjecByCloning(); // object to be cloned

    objecByNewKeyword.show("new keyword");
    objecByClassForName.show("using Class.forName and newInstance");
    objecByCloning.show("cloning");
    
  }
  

  public static ObjectCreation createObjecByNewKeyword(){
   
     ObjectCreation obj = new ObjectCreation();
     return obj;
  } 

 
  public static ObjectCreation createObjecByClassForName() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
   
     ObjectCreation obj = (ObjectCreation)Class.forName("ObjectCreation").newInstance();
     return obj;
  }


  public static ObjectCreation createObjecByCloning()throws CloneNotSupportedException{

     ObjectCreation obj = new ObjectCreation();
     ObjectCreation clone = (ObjectCreation)obj.clone();
     return clone;
  } 

  public void show(String msg){
     System.out.println("I am an Object created by " + msg);
  }
  
}

Output of the above program
I am an Object created by new keyword
I am an Object created by using Class.forName and newInstance
I am an Object created by using cloning

No comments:

Powered by Blogger.