Skip to main content

Section 8.3 Worked Example: Writing Classes - Constructors

Subsection 8.3.1 Subgoals for Writing a Class 2/4

  1. Name it

  2. Differentiate class-level (static) vs. instance/object-level variables

  3. Differentiate class-level (static) vs. instance/object behaviors/methods

  4. Define class variables (static) as needed ‘

    1. Name

    2. Data Type

    3. public / private / final

  5. Define instance variables (that you want to be interrelated)

    1. Name

    2. Data Type

    3. private

  6. Create constructor (behavior) that creates initial state of object

    1. public

    2. Same name as class

    3. No return type

    4. Default - no parameters

    5. Logic - initialize all variables

    6. Repeat as needed, adding parameters

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 8.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;
}

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

Figure 8.3.1.

Subsection 8.3.3 Practice Pages

You have attempted of activities on this page.