Facebook

Course Name Start Date Time Duration Registration Link
No Training Programs Scheduled ClickHere to Contact
Please mail To sudhakar@qtpsudhakar.com to Register for any training

Tuesday, March 12, 2019

Different ways to create Instance in Java

import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;

public class WaysToCreateObjects {

 public static void main(String[] args)
   throws InstantiationException, IllegalAccessException, ClassNotFoundException, CloneNotSupportedException,
   IOException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

  // method1 : Standard Technique
  Sample insta1 = new Sample();
  System.out.println("instance1 created");

  // method2 : By taking class name as string in Class
  Sample insta2 = (Sample) Class.forName("com.batch.ques.Sample").newInstance();
  System.out.println("instance2 created");

  // method3 : Creating new instance from another instance
  Sample insta3 = insta2.getClass().newInstance();
  System.out.println("instance3 created");

  // method4 : Creating new instance using class static method
  Sample insta4 = Sample.class.newInstance();
  // Sample.class.getConstructor().newInstance();
  System.out.println("instance4 created");

  // method5 : Reading new instance from Object Stream
  ObjectInputStream strm = new ObjectInputStream() {
  };
  Sample insta5 = (Sample) strm.readObject();
  System.out.println("instance5 created");

  // method6 : Cloning new instance from other instance
  /*
   * For cloning you must make sure that the class is implemented with Cloneable
   * interface and should have clone() method imlementation
   * 
   */
  Sample insta6 = (Sample) insta1.clone();
  System.out.println("instance6 created");
 }
}


No comments :

Post a Comment