Section 9.1 Worked Example: Writing Classes - Attributes
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.1.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.
For the first part, determine the appropriate attributes (data) to be stored and declare them
Subsection 9.1.2 SG1: Name it
We will call the class TimeType
Subsection 9.1.3 SG2: Differentiate class-level (static) vs. instance/object-level variables
class-level (static) data: one value shared between ALL instances instance-level data: each instance has its own copy
For time, we want all time instances to be in the same format so static data for format, everything else instance
Subsection 9.1.4 SG3: Differentiate class-level (static) vs. instance/object behaviors/methods
All methods will be instance level as the format will be fixed an unchangeable
Subsection 9.1.5 SG4: Define class variables (static) as needed
public class TimeType {
public static final boolean FORMAT24 = true;
}
Note the use of the
final
keyword to define FORMAT24
as a constant, which makes it safe to expose as public
. An alternate implementation might choose to make this value mutable, but private, using static methods to ssssssssaccess and alter it.Subsection 9.1.6 SG5: Define instance variables (that you want to be interrelated)
public class TimeType {
//static var
public static final boolean FORMAT24 = true;
//instance vars
private int hour;
private int minute;
private int second;
}
Practice Pages.
You have attempted of activities on this page.