Section 9.3 Worked Example: Writing Classes - Constructors
Subgoals for Writing a Class.
- Name it
- Differentiate class-level
static
vs. instance/object-level variables - Differentiate class-level
static
vs. instance/object behaviors/methods -
Define instance variables (that you want to be interrelated)
- Name
- Data Type
- private
-
Define class variables
static
as needed- Name
- Data Type
- public / private / final
-
Create constructor (behavior) that creates initial state of object
- Overloaded constructor (with as many parameters)
- 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
-
-
Write toString method
- public
- Returns String
- No parameters
- Logic - convert needed attributes to a format that can be printed
-
Write equals method
- public
- Returns boolean
- Parameter - instance of the class
- Logic - compare attributes for equity
- Create additional methods as needed
Subsection 9.3.1
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.
The attributes have been declared, now write a default and overloaded constructor.
Subsection 9.3.2 SG6: Create constructor (behavior) that creates initial state of object
6A, 6B, & 6C: All constructors are public, with no return type, and named the same as the class.
6D: We will start with the default constructor, which has no parameters.
All together, the default constructor has a header/signature of:
public TimeType() {
}
6E. Logic - initialize all variables
public TimeType () {
hour = 0;
minute = 0;
second = 0;
}
6F. Repeat as needed, adding parameters
public TimeType (int hr, int min, int sec) {
if (hr >=0 && hr <= 23)
hour = hr;
if (min >= 0 && min <= 59)
minute = min;
if (sec >= 0 && sec <= 59)
second = sec;
}
Subsection 9.3.3
We are now able to construct TimeType objects from the main method in two ways
public static void main (String [] args) {
TimeType midnight = new TimeType(); //call the default constructor
TimeType noon = new TimeType(12, 0, 0); //call an overloaded constructor
}
Update the UML Diagram
Practice Pages.
You have attempted of activities on this page.