In one of the java interview, the following question is asked:
In java is there a way to instantiate an object without using new
operator? I replied to him that there is no other way of instantiation. But he asked me how an object in java is instantiated with the configurations in an xml
file in java(in spring framework). I said, internally the spring uses reflection utils
to create an object with a new
operator. But the interviewer was not convinced with my answer.
I saw this link to be useful but there is a new
operator indirectly involved in one or the other internal methods.
Is there really a way to instantiate objects in java without using new
operator?
In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object.
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.
This is the easiest way to instantiate an object. It's as easy as creating a variable or calling a static method. There are no restrictions on where to create an object with a new keyword.
You can do it using the Java Reflection API. That's how the Spring framework's DI works (instantiating object from xml).
Class<YourClass> c = YourClass.class;
YourClass instance = c.newInstance();
Also,
Considering enum
to be a special class
, the instances of the enum are created without using new
Operator.
public enum YourEnum { X, Y }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With