8.3. Worked Example: Writing Classes - Getters and Setters¶
Subgoals for Writing a Class 3/4
Name it
Differentiate class-level (static) vs. instance/object-level variables
Differentiate class-level (static) vs. instance/object behaviors/methods
Define class variables (static) as needed ‘
Name
Data Type
public / private / final
Define instance variables (that you want to be interrelated)
Name
Data Type
private
Create constructor (behavior) that creates initial state of object
public
Same name as class
No return type
Default - no parameters
Logic - initialize all variables
Repeat as needed, adding parameters
Create 1 accessor and 1 mutator behaviors per attribute
Accessors
Name is get_<attr_name>
Public
Return type same data type as attribute
No parameters
Logic - return value
Mutators
Name is set_<attr_name>
Public
Return type is void
Parameter is same data type as attribute
Logic validates input parameter and sets attribute value
You can watch this video or read through the content below it.
Problem: We will be writing a class to represent an instance of time, like a specific time in the day.
Now write the appropriate accessors (getters) and mutators (setters).
SG7: Create 1 accessor and 1 mutator behaviors per attribute
There are 3 instance attributes, so we will need 3 getters and 3 setters
7A. Accessors
Name is get_<attr_name>
Public
Return type same data type as attribute
No parameters
Logic - return value
public int getHr() {
return hour;
}
public int getMin() {
return minute;
}
public int getSec() {
return second;
}
7B. Mutators
Name is set_<attr_name>
Public
Return type is void
Parameter is same data type as attribute
Logic validates input parameter and sets attribute value
public void setHr(int hr) {
if (hr >=0 && hr <= 23)
hour = hr;
}
public void setMin(int min) {
if (min >= 0 && min <= 59)
minute = min;
}
public void setSec(int sec) {
if (sec >= 0 && sec <= 59)
second = sec;
}
After writing getters and setters, this is a good time to review the structure of the class and refactor the overloaded constructor(s) to eliminate duplicate validation logic.
public TimeType (int hr, int min, int sec) {
setHr(hr);
setMin(min);
setSec(sec);
}
After working on the class definition, it is a good practice to test with a main driver program.
public static void main (String [] args) {
TimeType now = new TimeType();
now.setHr(14);
now.setMin(30);
now.setSec(45);
}
Practice Pages