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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
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.
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)
RegularEnumSetand another for many values calledJumboEnumSet