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
11 Answers
+ 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
+ 4
Your question is incomplete?
+ 4
constructor can be use to set value for private variables too
+ 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
}
+ 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);
+ 3
setter and getter is used when you want to access the private variable of your class outside the class
+ 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.
0
wanted to say " ot are Setters just used if you have more than 1 variabl?"
0
thanks for your aswers
0
and with constructors I can change the variable just once ?
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)?