Java: Difference between initializing by constructor and by static method?

后端 未结 2 373
再見小時候
再見小時候 2021-01-13 10:08

This might just be a question of personal taste and workflow, but in case it\'s more than that, I feel I should ask anyway.

In Java, what differences are there betwe

2条回答
  •  生来不讨喜
    2021-01-13 11:06

    There are both advantages and disadvantages of static factory methods.

    Advantages

    • Descriptive, meaningful names.
    • When invoked they can decide whether to return a new instance
    • They can return an object of any subtype of the return type
    • They reduce the verbosity of creating parameterized type instances

    Disadvantages

    • If you provide only static factory methods, classes without public or protected constructors cannot be subclassed
    • They are not readily distinguishable from other static methods

    Source: Effective Java, Second Ed.

提交回复
热议问题