- If you have not completed the exercise on The Time Class, do so now.
- Open TheTimeClass.java and add the toString method and add the following constructor.
public String toString(){ return this.hour + ":" + this.minute + ":" + this.second; } public TheTimeClass(int hour, int minute, int second){ this.hour = hour; this.minute = minute; this.second = second; }
- Attempt to compile the class.
$ javac TheTimeClass.java TheTimeClass.java:17: error: constructor TheTimeClass in class TheTimeClass cannot be applied to given types; TheTimeClass myTime = new TheTimeClass(); ^ required: int,int,int found: no arguments reason: actual and formal argument lists differ in length 1 error
The class doesn’t compile due to the new constructor added. If a class has an overloaded constructor then Java does not create a default no-argument constructor.
- Add the following constructor.
public TheTimeClass(){ this.hour = 0; this.minute = 0; this.second = 0; }
- Compile and run the program.
$ javac TheTimeClass.java $ java TheTimeClass 0:0:0
- Modify main to call the constructor that takes parameters.
public static void main(String[] args){ TheTimeClass myTime = new TheTimeClass(3,33,55); System.out.println(myTime.toString()); }
- Compile and run the program.
$ javac TheTimeClass.java $ java TheTimeClass 3:33:55
The complete class should 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 TheTimeClass(){ this.hour = 0; this.minute = 0; this.second = 0; } public TheTimeClass(int hour, int minute, int second){ this.hour = hour; this.minute = minute; this.second = second; } public static void main(String[] args){ TheTimeClass myTime = new TheTimeClass(3,33,55); System.out.println(myTime.toString()); } }
For more practice with constructors refer to the following video tutorial by LearningLad.
And for another tutorial on constructors and explaining the this keyword, refer to this tutorial by LearningLad.