Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of Avoiding 'new' Keword When Creating Object in Java

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?

like image 581
Razib Avatar asked Dec 19 '14 11:12

Razib


1 Answers

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.).

like image 52
Marko Topolnik Avatar answered Sep 28 '22 19:09

Marko Topolnik