I have found some blog where there is a suggestion of avoiding new
keyword while
creating object of a class. Some examples of creating object without the new
keyword are-
SampleObject obj = Class.forName("com.example.SampleObject").newInstance();
Or using clone()
method -
SampleObject obj1 = new SampleObject();
SampleObject obj2 = obj.clone();
Then here I have found some good examples of creating object without new
keyword
I can understand the advantages of 'Factory' pattern while avoiding new
keyword from main portion of code. If I am not using any design pattern (for creating objects) is there any benefit of creating object without the new
keyword? Or what are the reasons for creating of object without new
?
What you read in the blog must have been about factory methods and similar techniques, which don't avoid new
, but rather place it behind a more flexible API.
There are definetely no overarching downsides to the new
operator. It has been, and will remain, the staple of any Java code, and the most natural way to actually create an object, as opposed to satisfying a more generic concern, such as "provide me with an entry point to your API".
All other techniques that create objects without involving new
are special-purpose tools (cloning, deserialization, etc.).
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