I\'ve recently discovered an interesting way to create a new instance of an object in Google Guava and Project Lombok: Hide a constructor behind a static creator method. Thi
i got very interesting reason to hide constructor check it and please let me know if there is any other alternative to achieve this
enter code here
Class A
{
String val;
protected A( )
{
}
protected A(String val)
{
this.val=val;
}
protected void setVal( String val)
{
this.val=val;
}
public String getVal()
{
return val;
}
}
class B extends A
{
B()
{
super();
}
public val setVal(String val)
{
super.val=val;
}
}
class C extends A
{
C(String val)
{
super(val);
}
}
null
There are a number of reasons why you might prefer a static factory method instead of a public constructor. You can read Item 1 in Effective Java, Second Edition for a longer discussion.
EnumSet.of(E)
will return a different type if the emum type has very few elements vs if the enum type has many elements (Edit: in this particular case, improving performance for the common case where the enum doesn't have many elements)Integer.valueOf(x)
will, by default, return the same object instance if called multiple times with the same value x
, if x
is between -128 and 127.java.util.concurrent.Executors
.Collections
hides many types. Instead of having a Collections
class with many static methods, they could have created many public classes, but that would have been harder for someone new to the language to understand or remember. List<String> strings = new ArrayList<String>()
in Guava you can do List<String> strings = Lists.newArrayList()
(the newArrayList
method is a generic method, and the type of the generic type is inferred).For HashBiMap
, the last reason is the most likely.