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

后端 未结 2 403
再見小時候
再見小時候 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:02

    The difference is a static factory method is more flexible. It can have all sorts of ways to return an instance. It can do other side stuff. It can have a more descriptive name. It can be invoked by its simple name (e.g. foo(args)) by static import or inheritance.

    The constructor call is more certain - the caller knows exactly what's happening - a new instance of that exact class is created.

提交回复
热议问题