200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > java 静态方法 构造方法 Java构造函数和静态方法

java 静态方法 构造方法 Java构造函数和静态方法

时间:2020-04-17 11:42:14

相关推荐

java 静态方法 构造方法 Java构造函数和静态方法

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.

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();

}

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.

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。