Carleton University - SYSC 2004
Part 3: Problem Solving
Final Exam BreakdownQuestion 1: Define a base class to represent a Clock. Your class should have instance variables for hours, minutes and seconds. Represent means: class fully functional. Valid integers for hour is in the range of 0 – 24, valid integers for minute is in the range 0 – 59, valid integers for second is in the range 0 – 59.
To solve this, we create a Clock class with validation in the constructor to ensure hour, minute, and second values fall within valid ranges. It should also include a method to display the time.
public class Clock {
private int hour;
private int minute;
private int second;
public Clock(int hour, int minute, int second) {
if (hour < 0 || hour > 24 || minute < 0 || minute > 59 || second < 0 || second > 59) {
throw new IllegalArgumentException("Invalid time values");
}
this.hour = hour;
this.minute = minute;
this.second = second;
}
public void displayTime() {
System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
}
}Question 2: Define a derived class to represent an alarm clock. Use the Clock class, created in number 1 above, as your base class. An alarm clock should include a time to sound the alarm as well as methods to set the alarm.
We create an AlarmClock class that extends Clock and adds fields and methods for managing an alarm time.
Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 3 more lessons in Carleton University - SYSC 2004.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.