Constructors and "Setters" // JAVA | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Constructors and "Setters" // JAVA

Hello, Why do we need to use a "setter" with constructors? Is it good practice and why? The two bits of code below do the same thing, which option should I use and why? To me, it makes more sense to use option 2 as it's easier (less code = less typing = more productive = easier to meet deadlines). //OPTION 1 class Vehicle { Vehicle(int ms) { this.setMaxSpeed(ms); } public void setMaxSpeed(int ms){ this.MaxSpeed = ms; } } // OPTION 2 class Vehicle { Vehicle(int ms) { this.MaxSpeed = ms; }

13th Jan 2017, 8:18 PM
Daniel Stanciu
Daniel Stanciu - avatar
7 Answers
+ 7
1st one Reasons, in my opinion, maybe you will need some other setters, for example MinSpeed, so in order to differenciate one from another, you will need to use the first option, where you can add 'public void setMinSpeed(int ms)' with its this.MinSpeed. That's how I imagine doing that, idk if that's true, someone correct me if I'm wrong..
13th Jan 2017, 8:13 PM
Filip
Filip - avatar
+ 7
Yea, you can. But I find it better to be written like in option 1, idk, it looks better to me
13th Jan 2017, 8:20 PM
Filip
Filip - avatar
+ 7
I think it's safer, in some way, to have a setter for each variable.. I forgot about that. But I told you what I think, and what I remember I was doing few years ago
13th Jan 2017, 8:25 PM
Filip
Filip - avatar
+ 3
@SuspiciousUser Brilliant answer, thanks a lot!
14th Jan 2017, 12:08 PM
Daniel Stanciu
Daniel Stanciu - avatar
+ 2
@Filip Thanks for your answer! For multiple attributes, you could do this: class Vehicle { private int MaxSpeed; private int wheels; private String color; private double fuelCapacity; Vehicle(int MaxSpeed, int wheels, String color, double fuelCapacity) { this.setMaxSpeed = MaxSpeed; this.wheels = wheels; this.color = color; this.fuelCapacity = fuelCapacity; }
13th Jan 2017, 8:20 PM
Daniel Stanciu
Daniel Stanciu - avatar
+ 2
@Filip The thing is, with option 1, you would have to write a setter method for every single variable, so what if you have 100 variables? I would like to know why option 1 is recommended.
13th Jan 2017, 8:23 PM
Daniel Stanciu
Daniel Stanciu - avatar
+ 1
@SuspiciousUser Thanks! I sort of get it, but please, could you give me an example? I want to understand it fully, I would really appreciate it
14th Jan 2017, 1:05 AM
Daniel Stanciu
Daniel Stanciu - avatar