Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Explain the following Java Class. // Represents a time span of hours and minu

ID: 3568326 • Letter: 1

Question

1. Explain the following Java Class.

// Represents a time span of hours and minutes elapsed.

// Class invariant: minutes < 60

public class TimeSpan {

private int hours;

private int minutes;

// Constructs a time span with the given interval.

// pre: hours >= 0 && minutes >= 0

public TimeSpan(int hours, int minutes) {

this.hours = 0;

this.minutes = 0;

add(hours, minutes);

}

// Adds the given interval to this time span.

// pre: hours >= 0 && minutes >= 0

public void add(int hours, int minutes) {

this.hours += hours;

this.minutes += minutes;

// convert each 60 minutes into one hour

this.hours += this.minutes / 60;

this.minutes = this.minutes % 60;

}

// Returns whether o is a TimeSpan representing the same

// number of hours and minutes as this TimeSpan object. public boolean equals(Object o) {

if (o instanceof TimeSpan) {

TimeSpan other = (TimeSpan) o;

return hours == other.hours && minutes == other.minutes;

}

else { // not a TimeSpan object

return false;

}

}

// Returns a String for this time span such as "6h15m".

public String toString() {

return hours + "h" + minutes + "m";

}

}

Explanation / Answer

Explanation:

The TimeSpan class is composed of two attributes and three methods.
The attributes are as follows:
1) hours: hours is an integer data type stores the value of the hours in time
2) minutes: minutes is also an integer data type stores the value of the minutes in time

The methods of TimeSpan class are as follows:
1) add() method:
The add() method adds the new hours value and new minutes value to the previously existed hours value and minutes value respectively. After adding the values it converts each 60 minutes into one hour.

2) equals() method:
equals() method compares the current TimeSpan with the object of another TimeSpan which is passed as parameter to the method.

3) toString() method:
toString() method is just a description for the class. It returns the end result of the class. It returns the hours and minutes after converting them to the string data type.

The Constructor TimeSpan initializes the attributes, hours and minutes and it invokes the add() method.