When you are first starting to program, some of the most commonly used methods are called Getters and Setters (some like to call them Mutators and Accessors). These methods deal directly with attributes of the object they are associated with.
When we are working with an object, sometimes we will need to know certain pieces of information about the object that only the object can tell us reliably.
Recall the DrawSquare
class that we worked with earlier. We might remember the length of a side, but if that length has changed for some reason during the life of the object, we might be in for a surprise if we used that value.
sideLength
and provide a Getter method along the lines of double getSideLength()
. The Getter method’s purpose would be to give us current information about that object. getSideLength
method allows other objects to look at the data in our DrawSquare
object and storing the length in a private variable prevents these objects from directly accessing the length.What happens if we do want to change that side length from outside our class?
As it stands right now, that would not be possible.
DrawSquare
class that would do this for us, void setSideLength(double d)
. This method’s basic purpose is to change the value of the sides for us, but it could also do a bit more. setSideLength
a value of negative 10? Our square could obviously not exist with a negative side value, so our Setter program should check for validity of the values. Setters can often do calculations for us when necessary, so they are not always simply changing a value and doing nothing else. boolean
which will return true if the value was valid and false if the value was not. This lets clients know if their value was accepted or not. If the client sends an invalid value to a method, it is usually good for them to know that they tried to use the method incorrectly.Last modified: December 12, 2022
Back to Lifetime, Initialization,...