What are all the different ways to create an object in Java?
There are various ways:
- Through
Class.newInstance
. - Through
Constructor.newInstance
. - Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
- Through
Object.clone
(does not call a constructor). - Through JNI (should call a constructor).
- Through any other method that calls a
new
for you. - I guess you could describe class loading as creating new objects (such as interned
String
s). - A literal array as part of the initialisation in a declaration (no constructor for arrays).
- The array in a "varargs" (
...
) method call (no constructor for arrays). - Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
- Causing an exception to be created and thrown by the runtime. For instance
throw null;
or"".toCharArray()[0]
. - Oh, and boxing of primitives (unless cached), of course.
- JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
- For completeness (and Paŭlo Ebermann), there's some syntax with the
new
keyword as well.
There are four different ways to create objects in java:
A. Using new
keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();
B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
You can read them from here.