OOP 4. Data+Constructor - TimeOfDay

Purpose of this lesson:

TimeOfDay1 Example - No constructor

Let's say that we want to represent a time of day necessary for representing when an appointment is scheduled. It won't represent the day, only the time as hour and minute. Here's a start using a 24 hour clock (00:00 to 23:59).

TimeOfDay1.java

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
// File   : oop/timeofday/TimeOfDay1.java
// Purpose: A 24 hour time-of-day class.
//          This simple value class has public fields.
// Author : Fred Swartz - 2005-05-30 - Placed in public domain.

public class TimeOfDay1 {
    public int hour;
    public int minute;
}

Test program

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
// File   : oop/timeofday/TimeTest1.java
// Purpose: Test the TimeOfDay1 class.
//          Shows use of dot notation to select public fields.
// Author : Fred Swartz, 2005-05-04, Placed in public domain.

import javax.swing.*;

public class TimeTest1 {
    public static void main(String[] args) {

        //... Create a new TimeOfDay object.
        TimeOfDay1 now = new TimeOfDay1();

        //... Set the fields.
        now.hour   = 10;  // Set fields explicitly.
        now.minute = 32;

        //... Display the time by referencing the fields explicitly.
        JOptionPane.showMessageDialog(null, now.hour + ":" + now.minute);
    }
}

TimeOfDay1b.java - As above, but with constructor

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
// File   : oop/timeofday/TimeOfDay1b.java
// Purpose: A time-of-day class with constructor, which provides
//          a more convenient and conventional way to build objects.
//          The constructor is overloaded (more than one version) for
//          more convenience.
// Author : Fred Swartz, 2007-02-27, Placed in public domain.

public class TimeOfDay1b {
    public int hour;
    public int minute;

    //==================================================== constructor    //Note 1
    public TimeOfDay1b(int h, int m) {
        hour   = h;   // Set the fields from the parameters.
        minute = m;
    }
}

Notes

  1. Constructors have no return type, and have the same name as the class.

Test program using constructor

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
// File   : oop/timeofday/TimeTest1b.java
// Purpose: Test the TimeOfDay1b class.
// Author : Fred Swartz, 2007-02-27, Placed in public domain.

import javax.swing.*;

public class TimeTest1b {

    public static void main(String[] args) {

        //... Create a TimeOfDay1b object for 10:30 in the morning.
        TimeOfDay1b now = new TimeOfDay1b(10,30);

        //... Display it.
        JOptionPane.showMessageDialog(null, now.hour + ":" + now.minute);
    }
}