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

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

问题描述

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

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.

我知道,一旦使用new"关键字实例化一个类,构造函数就会在类中初始化一个实例变量.

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

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

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

推荐答案

当你想创建一个对象的新实例时,你应该使用构造函数的方法,其中的值已经填充(一个准备使用的对象,填充了值).这样你就不需要为对象中的每个字段显式调用 setter 方法来填充它们.

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 call the setter methods for each field in the object to populate them.

当您想在创建对象后更改字段的值时,您可以使用 setter 方法设置值.

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

例如:-

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 :(

正如 Axel 提到的,如果你想创建不可变的对象,你不能使用 setter-methods 方法.我不会说所有的东西都必须在构造函数中初始化,因为存在不同的方法,比如延迟评估甚至可以用于不可变对象.

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天全站免登陆