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

非 Y 不嫁゛ 提交于 2019-12-19 08:02:14

问题


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 between creating an instance via constructor and via a static method (which returns the instance)? For example, take this bit of code from a project I'm working on (written up by hand at time of posting, so some shortcuts and liberties are taken):

Plugin main;
Map<int, int> map;

public Handler(Plugin main) {
    this.main = main;
}

public static Handler init(Plugin main) {
    Handler handler = new Handler(main);
    handler.createMap();
}

public void createMap() {
    this.map = Maps.newHashMap();
}

In cases like this, what would the difference be between using

Handler handler = new Handler(this);

and

Handler handler = Handler.init(this);

in the Plugin class, besides the fact that createMap() runs only in the latter because it's not called in the constructor?

To clarify, in this case, Plugin is considered the main class.

I know enough Java syntax to be able to write intermediate-level plugins, but not enough about Java itself to know the difference between these two ways of doing this.

EDIT: For instance, the Maps class that I used to create the Map uses a static factory method (I hope I'm using that term correctly) called using the class instead of an object.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15102384/java-difference-between-initializing-by-constructor-and-by-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!