java lab problems Time1 Declare a class Time1. Declare a constructor initializin
ID: 3843169 • Letter: J
Question
java lab problems
Time1 Declare a class Time1. Declare a constructor initializing values of three instance variables i.e. hours, minutes and seconds. Knowing that the instance variables of the class Time1 has been declared to be private. getters: implement the access methods that return the value of hours, minutes and seconds respectively. Create the following two class methods: void increase(): increment the time by one seconds and print them. boolean equals(Time1 other): returns true if and only if other designates an object that has the same content as this one. Time2 Let's consider an alternative way of representing time values. Create a new class called Time2. Inheritance: Class Time2 inherits Time1 and add another instance variable millisecond and initialize it along with instance variables of Time1 using constructor. Override method boolean equals (Time other) of Time1 as now it includes another instance variable i e. milliseconds.Explanation / Answer
TIME1 CLASS
import java.util.*;
public class Time1{
private int hours;
private int minutes;
private int seconds;
public Time1(int hours,int minutes,int seconds){
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public int getHours(){
return hours;
}
public int getMinutes(){
return minutes;
}
public int getSeconds(){
return seconds;
}
public void increase(){
seconds = seconds+1;
System.out.println(seconds);
}
public boolean equals(Time1 other){
if(other == this) return true;
if(other != this) return false;
if(getClass() != other.getClass()) return false;
Time1 time1 = (Time1)other;
return (hours == time1.hours && minutes == time1.minutes && seconds == time1.seconds);
}
}
TIME2 CLASS
import java.util.*;
public class Time2 extends Time1{
private int millisec;
Time2(int hours,int minutes,int seconds,int millisec){
super(hours,minutes,seconds);
this.millisec = millisec;
}
public int getMillisec(){
return millisec;
}
public boolean equals(Time2 other){
if(other == this) return true;
if(other != this) return false;
if(getClass() != other.getClass()) return false;
Time2 time2 = (Time2)other;
return (hours == time2.hours && minutes == time2.minutes && seconds == time2.seconds && millisec == time2.millisec);
}
}
TIME CLASS
import java.util.*;
public class Time{
public static void main(String[] args){
// constructor intialization
Time2 time2 = new Time2(2,30,2,10);
//prints hours minutes seconds milliseconds
System.out.println("Hours "+time2.getHours());
System.out.println("Minutes "+time2.getMinutes());
System.out.println("Seconds "+time2.getSeconds());
System.out.println("Milliseconds "+time2.getMillisec());
//Increase the seconds by 1
System.out.println("Increased seconds "+increase());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.