- 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; }
- Add a constructor for the class.
public TheTimeClass(){ this.hour = 0; this.minute = 0; this.second = 0; }
- Add a toString method to TheTimeClass.
public String toString(){ return this.hour + ":" + this.minute + ":" + this.second; }
- 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()); }
- Compile and run the program.
$ javac TheTimeClass.java $ java TheTimeClass 0:0:0
- 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()); } }
- 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.
- 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()); } }
- 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.