Design a Time class. A time object should have an instance variable for the numb
ID: 3775872 • Letter: D
Question
Design a Time class. A time object should have an instance variable for the number of hours, minutes, and seconds. in addition to the 3 instance variables, write 2 constructors. One constructor should take in the hours and minutes only. second constructor should take in the number of hours, minutes, and seconds. Encapsulate your data and remember to provide a getter and setter for each instance variable. Also include a to String method to output the information. Sample output: 9:40:26 Type the code in jGrasp. Make sure it compiles and write client code to test your Time class.Explanation / Answer
import java.util.*;
import java.lang.*;
class Time
{
private int hours;
private int minutes;
private int seconds;
public Time(int hours,int minutes,int seconds) //constructor with hours,minutes and seconds
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public Time(int hours,int minutes) //constructor with hours and minutes
{
this.hours = hours;
this.minutes = minutes;
}
public void setHours(int hours) //set and get methods for variables hours,minutes and seconds
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setMinutes(int minutes)
{
this.minutes = minutes;
}
public int getMinutes()
{
return minutes;
}
public void setSeconds(int seconds)
{
this.seconds = seconds;
}
public int getSeconds()
{
return seconds;
}
public String toString() //toString() method
{
return "Time :"+hours +":"+minutes+":"+seconds;
}
}
class TimeTest
{
public static void main (String[] args)
{
Time t = new Time(11,50,30);
System.out.println(t.toString());
Time t1 = new Time(2,48);
System.out.println("Hours:"+t1.getHours());
System.out.println("minutes:"+t1.getMinutes());
}
}
output: