java中构造方法和静态方法的区别,Java:通过构造函数和静态方法初始化之间的区别?...

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 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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值