Java构造函数和静态方法 [英] Java Constructor and static method
问题描述
我何时应该使用构造函数,何时应该使用静态方法?
When should I use a constructor and when should I use static method?
您能用上面的小片段解释一下吗?我浏览了几个线程,但我仍然不清楚这一点。
Can you explain above with small snippet? I skimmed through a few threads but I'm still not clear with this.
推荐答案
当你只想要时使用公共构造函数返回一个类型的新对象,你想要简单。
Use a public constructor when you only ever want to return a new object that type and you want simplicity.
一个很好的例子是StringBuilder,因为它是可变的,你可能每次都想要一个新对象。
A good example is StringBuilder as it's mutable and you are likely to want a new object each time.
public String toString() {
StringBuilder sb = new StringBuilder();
// append fields to the sb
return sb.toString();
}
当您可能想要重复使用对象时使用静态因子方法(尤其是如果是不可变的),你可能想要返回一个子类,或者你想要describeice构造。一个很好的例子是EnumSet,它有许多静态工厂,即使有些工具具有相同的参数,也会做不同的事情。
Use a static factor method when you might want to re-use objects (esp if immutable), you might want to return a sub-class or you want descriptice construction. A good example is EnumSet which has a number of static factories which do different things even though some have the same arguments.
EnumSet.noneOf(RetentionPolicy.class);
// has the same arguments, but is not the same as
EnumSet.allOf(RetentionPolicy.class);
在这种情况下,使用静态工厂可以清楚说明这两种构造方式之间的区别设置。
In this case, using a static factory makes it clear what the difference between these two ways of construction the set.
此外,EnumSet可以返回两个不同的实现,一个针对具有少量值的枚举进行优化(< = 64) RegularEnumSet
和另一个叫做 JumboEnumSet
Also EnumSet can return two different implementations, one optimised for enums with a small number of values (<= 64) RegularEnumSet
and another for many values called JumboEnumSet
这篇关于Java构造函数和静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!