Getter and Setter Functions
We have already covered this a little in our previous lesson. In this lesson, we will be explaining the usage of getter and setter functions in more detail.

Suppose that you are using the Shape
class and all its subclasses to create a very large drawing project with many other collaborators. Many developers will be importing your drawables
package (suppose this contains all your classes) and instantiating many objects. Among them, one person mistakenly puts this line of code somewhere in their large file.
1Rectangle rect = new Rectangle(5,6);
2// Do some stuff
3rect.height = -1
4// Try to do something like draw the rectangle on the screen
Later in his own implementations, he finds very weird bugs that should not be there. He is not even opening the file where he put the above line. Imagine the horrific nights he and others might have just because your class does not have any way to validate its attributes.
Somehow, you should check if the assigned value to the property is valid or not. The best way is to validate a value is to raise an Exception when a user attempts to set an invalid value. However, we will be covering exceptions in our next lesson. For now, we will just print to the console that the user is attempting to set an invalid value. Unfortunately, we cannot validate the value if it is directly assigned to the attribute which is why we need setter methods. When you use a setter, you can make sure that you are getting the correct value for the correct attribute.
There are other reasons you should use setter methods. For example, you should use setter methods if you always want to convert the given value to something else before assigning it to a variable or if you want to do some database/internet operations while setting attributes.
1// Rectangle.java
2public class Rectangle extends Shape {
3 // Make these attributes protected/private so others will not use it outside
4 protected int height;
5 protected int width;
6
7 // getters and setters will always be public
8 // getters
9 public int getWidth() { return width; }
10 public int getHeight() { return height; }
11
12 // setters
13 public void setWidth(int width) {
14 if(width <= 0) {
15 System.out.println("Invalid width for Rectangle");
16 return;
17 }
18 this.width = width;
19 }
20 public void setHeight(int height) {
21 if(height <= 0) {
22 System.out.println("Invalid height for Rectangle");
23 return;
24 }
25 this.height = height;
26 }
27 // Other methods and attributes
28}