Notice in the TimeBasicsTest.java that when we instantiate/construct a
TimeBasics object we set all the values to zero and then set the time
based on the user's inputs in the next line of code. We repeat the
code here for ease of reference.
This code is contained in the actionPerformed( ) method that gets executed if the user clicks on the button and has given valid inputs.
But we can improve on this somewhat by creating another constructor with the same name, but with a different number of arguments. Doing this is called constructor overloading. Remember, the constructor must have the same name as the overall inclusive class. How the compiler differentiates between which constructor you want to use depends on how many arguments you pass when you invoke it.
With this in mind we have slightly modified the TimeBasics.java class to contain another constructor. You should still call this TimeBasics.java and compile it using the
javac -d C:\j2sdk1.4.0\jre\classes TimeBasics.java
command. The only changes in the code are highlighted in blue.
// This class maintains the time in a 24 hour format
// and has a method to convert this to an AM/PM scale
public class TimeBasics extends Object
Now you can slightly modify the TimeBasicsTest.java to construct/instantiate the TimeBasics object in one command. The only change to the code is highlighted in blue.
TimeBasics thisTime = new TimeBasics(hoursInput, minutesInput, secondsInput);
public class TimeBasicsTest extends JApplet implements ActionListener
|Again, due to the package the code will run wherever
you want it to on the same machine. You do not need to specify any
special path in the compilation command.
will still work.