0

Hey are constructors and setters almost the same if you have just 1 variable? Setters just used if you have more than 1 variabl

17th Mar 2017, 3:56 PM
jack
jack - avatar
11 Respuestas
+ 5
I think it's all up to you if you did not need to set the value again then there is no point for setting the setter
17th Mar 2017, 4:06 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 4
Your question is incomplete?
17th Mar 2017, 4:02 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 4
constructor can be use to set value for private variables too
17th Mar 2017, 4:04 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 4
Yes, you are able to set the value of the variable when you called the constructor during instantiation of the object and only once. For example you have a class class Car { private int tyreNumber; Car(int number) { tyreNumber = number; } public static void main(String[] args){ Car car = new Car(4); //however you are able to change the value //or should I said change the object entirely car = new Car(6); //by doing this you actually did not change //the value but you instantiate a new object }
17th Mar 2017, 5:32 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 4
yeah for example refer back previous code and add on Class Car { void serTyreNumber(int number) { tyreNumber = number; } } in the main: Car car = new Car(4); //will print 4 System.out.println(car.tyreNumber); //the same object or car but //changed tyre number car.setTyreNumber(6); //will print 6 System.out.println(car.tyreNumber);
18th Mar 2017, 1:19 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 3
setter and getter is used when you want to access the private variable of your class outside the class
17th Mar 2017, 4:03 PM
Heng Jun Xi
Heng Jun Xi - avatar
+ 1
No both are different as constructor is called while object is created for the first time. Setter functions may be needed in course of execution where value has to be modified. In Java, if you don't define any constructor, java automatically defined for you, but that is not true for setter functions.
17th Mar 2017, 4:43 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
0
wanted to say " ot are Setters just used if you have more than 1 variabl?"
17th Mar 2017, 4:04 PM
jack
jack - avatar
0
thanks for your aswers
17th Mar 2017, 5:20 PM
jack
jack - avatar
0
and with constructors I can change the variable just once ?
17th Mar 2017, 5:21 PM
jack
jack - avatar
0
thx Heng now I get it. so with a setter you can change the value than from for example car (6) or car (4)?
18th Mar 2017, 12:00 PM
jack
jack - avatar