Tino APCS

Getters and Setters

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.

Why getters?

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.

  • Here we would want to store the side length in a private instance variable 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.
  • We don’t want to let other objects access the side length directly, because they might alter that data when we don’t want them to. The 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 about setters?

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.

  • However, we could create a Setter method in the 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.
  • For instance, what if someone passed 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.
  • Often, Setter methods are given a return type of 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.

Dark Mode

Outline