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

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



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();
Updated on: 2020-06-16T09:03:59+05:30

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements