Print Page Print Page

CH11 – The Time Class and Constructors

  1. Create a new class named TheTimeClass and add the following instance variables.
public class TheTimeClass {
  private int hour;
  private int minute;
  private int second;
  public int hourTwo;
}
  1. Add a constructor for the class.
public TheTimeClass(){
  this.hour = 0;
  this.minute = 0;
  this.second = 0;
}
  1. Add a toString method to TheTimeClass.
public String toString(){
  return this.hour + ":" + this.minute + ":" + this.second;
}
  1. Add a main method to the class with the following code.
public static void main(String[] args){
  TheTimeClass myTime = new TheTimeClass();
  System.out.println(myTime.toString());
}
  1. Compile and run the program.
$ javac TheTimeClass.java
$ java TheTimeClass
0:0:0
  1. Remove the constructor from TheTimeClass. The complete class should now appear as follows.
public class TheTimeClass {
  private int hour;
  private int minute;
  private int second;

  public String toString(){
    return this.hour + ":" + this.minute + ":" + this.second;
  }

  public static void main(String[] args){
    TheTimeClass myTime = new TheTimeClass();
    System.out.println(myTime.toString());
  }
}
  1. Compile and run the program.
$ javac TheTimeClass.java
$ java TheTimeClass
0:0:0

The results are the same as before. Java initializes class variables to their default value, which for integers is zero. A class constructor taking no arguments is the default constructor and is strictly optional when no alternative constructors – as you see in the next exercise – are used.

  1. Now remove the toString method.
public class TheTimeClass {
  private int hour;
  private int minute;
  private int second;

  public static void main(String[] args){
    TheTimeClass myTime = new TheTimeClass();
    System.out.println(myTime.toString());
  }
}
  1. Compile and run the program.
$ javac TheTimeClass.java
$ java TheTimeClass
TheTimeClass@6d06d69c

Notice that now the class’s location is printed rather than its value. When you define your own class you can create a toString method, as every Java class has a built-in toString method. Unless you define your own, your class’s default behavior is to return its location in memory as a string.