What are all the ways an object can be created in Java?

Java 8Object Oriented ProgrammingProgramming

You can create an object

Using new keyword.

Sample obj = new Sample();
  • Using the newInstance() method and Class.forName() method.
Sample obj2 = (Sample) Class.forName("Sample").newInstance();
  • Using the clone() method by implementing Cloneable Interface (marker).
Sample obj3 = (Sample) obj1.clone();
  • Using class loader.
Object obj4 = Sample.class.getClassLoader().loadClass("Sample");
  • Using the constructor class from lang.reflect.
Class cls = Sample.class;
Constructor obj = cls.getDeclaredConstructors()[0];
Sample obj5 = (Sample) obj.newInstance();
raja
Published on 08-Jan-2018 11:24:01
Advertisements