Setter methods or constructors
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。
Say we have a class, named Counter:
public class Counter{
int count;
//constructor
public Counter(int c){
count = c;
}
public void setCounter(int newCounter){
count = newCounter;
}
}
In the class above, when you want to create a new Counter object, you would use a constructor and set the count variable within that. like so:
Counter myCounter = new Counter(1);
If you want to change the count variable during runtime, you would use the setter method:
myCounter.setCounter(2);
链接地址: http://www.djcxy.com/p/18008.html
上一篇: 调用超类构造函数的规则是什么?
下一篇: Setter方法或构造函数