简体   繁体   中英

when we have setter for setting value then why do we use parameterized constructor

When we have setter function for setting value then why do we need parameter constructor ? is it necessary to use ? is it good if we want to use constructor instead of setter and after that can we access our data using getter functions?

The job of the constructor is to construct the object in such a way that it is in a usable state. If this requires arguments to the ctor it should get them so the object can be fully formed when the constructor finishes. Constructing an object in a partially usable state and then relying on users to remember to call specific setters before they are allowed to use the object is quite error prone. Setters are fine for changing things after object creation but calling them should not be a requirement in order to construct a usable object.

If you do not construct a usable object upon creation, for example by using a parameterized constructor, you may run into issues if you/the user forgets to use your setters to actually give the object's parameters any real values.

It may be that you just return a bogus/zero value, which gives unexpected results, or it could cause the program to crash if you try to access some bit of memory that you don't have access to.

If I've misinterpreted your question, and you simply mean why do this:

MyClass(int a, int b) {
    myPrivateIntA = a;
    myPrivateIntB = b;
}

Instead of this:

MyClass(int a, int b) {
    setPrivIntA(a);
    setPrivIntB(b);
}

I suppose you could use the latter, if you need to do some kind of validation before setting your values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM