+ 1
What are the differences between constructor with arguments and setter in java?
When we create constructor with arguments in java and also setter method it's look like same most of the time it's confusing people to differentiate between them.
3 Answers
+ 1
a constructor is a constructor
it's purpose is to write codes in it
that you want to include
when the object is created
a constructor can take arguments or
not . you might want when creating
a person object to specify it's name
at the same time
a setter is a method. it is used to
modify variables that you don't want
to be made public like the bank balance
variable.
you don't want the user to make
his balance drop to -4 for ex
so you set a method which deals with the
variable and checks condition
class something(){
constructor(){
}
method setter(){
}
}
see an illustration here
https://github.com/Abdur-rahmaanJ/Java-codes/blob/master/bankAccount%20Encapsulation%20and%20Constructor%20illustration.java
see the setBalance setter
see there are also 2 constructor
one for instantiating with parameter
one without
hope it helps!
+ 1
A constructor is the first method that is being called when you make object for the class and you can send values as parameters in it for initialization Example: if you want to initialize counter value , ..etc. but setter is a method that is made to set values for private variables which can vary according to the input of the user every time so when the user want to change the value of one variable you call the setter sending the new value to it but if you used constructor as a setter that means that if the user wants to change the value of a variable you are going to make new object of the class which is a total waste of memory and CPU cycles
0
constructors are one off calls. setter and getter methods are not. you can for instance, set date of birth over a setter and getter call to find age where the calculation is invisible to the caller.