Setter方法或构造函数 [英] Setter methods or constructors

查看:231
本文介绍了Setter方法或构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经看到了两种在Java中设置变量值的方法。有时,使用带有参数的构造函数,其他的setter方法用于设置每个变量的值。



我知道构造函数初始化类中的一个实例变量,一旦类使用new关键字实例化。



但是我们什么时候使用构造函数,什么时候使用setter?

解决方案

当您要创建对象的新实例时,应使用构造函数方法,其中已填充值(已填充值的即可使用对象)。这样,您不需要显式地坐下并调用对象中每个字段的setter方法来填充它们。



您可以使用setter方法设置值

  MyObject obj1 = new MyObject(setSomeStringInMyObject); //构造方法
// Yippy,我可以使用我的obj1,因为值已经填充
//但即使在这之后,我可以更改值
obj1.setSomeString(IWantANewValue ); //如果需要,使用setter更改值。
..
MyObject obj2 = new MyObject();
obj2.setSomeString(setSomeStringNow); // Setter方法
//值未填充 - 我不得不这样做。悲伤:(

像Axel所说,如果你想创建不可变的对象,使用setter方法的方法我不会说一切都必须在构造函数中初始化,因为存在不同的方法,如lazy-evaluation,甚至可以用于不可变对象。


so far I have seen two approaches of setting a variable's value in Java. Sometimes a constructor with arguments is used, others setter methods are used to set the value of each variable.

I know that a constructor initialises an instance variable inside a class once a class is instantiated using the "new" Keyword.

But when do we use constructors and when do we use setters?

解决方案

You should use the constructor approach, when you want to create a new instance of the object, with the values already populated(a ready to use object with value populated). This way you need not explicitly sit and call the setter methods for each field in the object to populate them.

You set the value using a setter approach, when you want to change the value of a field, after the object has been created.

For example:-

MyObject obj1 = new MyObject("setSomeStringInMyObject"); // Constructor approach
// Yippy, I can just use my obj1, as the values are already populated
// But even after this I can change the value
obj1.setSomeString("IWantANewValue"); // Value changed using setter, if required.
..
MyObject obj2 = new MyObject();
obj2.setSomeString("setSomeStringNow"); // Setter approach
// values weren't populated - I had to do that. Sad :(

And as Axel mentioned, if you want to create immutable objects, you cannot use setter-methods approach. I won't say everything has to be initialised in the constructor because different approaches exist, like lazy-evaluation which can be used even with immutable objects.

这篇关于Setter方法或构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆