Answer:
The Date class below is created using Java.
- public class Date {
- private int day;
- private int month;
- private int year;
- public Date(int d, int m, int y)
- {
- setDay(d);
- setMonth(m);
- this.year = y;
- }
- public void setMonth(int m)
- {
- if(m >= 1 && m <= 12)
- {
- this.month = m;
- }
- else
- {
- throw new IllegalArgumentException("Input Month must be between 1 - 12");
- }
- }
- public void setDay(int d)
- {
- if(d >=1 && d <=31)
- {
- this.day = d;
- }
- else
- {
- throw new IllegalArgumentException("Input Day must be between 1 - 31");
- }
- }
- public void printDate()
- {
- System.out.println(this.month + "/" + this.day + "/" + this.year);
- }
- }
Step-by-step explanation:
Line 1:
- Create a class and name it as Date
Line 3-5:
- Define three properties/attributes in the Date class which are day, month and year.
- The data type of the properties are defined as integer
Line 7-13:
- Create a class constructor to initialize the values for the properties (day, month and year).
- To initialize the day and month, setDay() and setMonth() setter methods are called. This is to ensure the day and month are within the range of 1-31 and 1-12, respectively.
Line 15-25:
- Create setMonth() setter method with one parameter m to accept one input value.
- The setMonth() method will check the input value m to see if it is bigger or equal to 1 and less than or equal to 31 (the valid range). If not, an error will be thrown.
Line 27 - 37:
- Create setDay() setter method with one parameter d to accept one input value.
- The setDay() method will check the input value m to see if it is bigger or equal to 1 and less than or equal to 12 (the valid range). If not, an error will be thrown.
Line 39 - 42:
- Create printDate() method to display the date as month/day/year (ie 10/1/1999)
- Use Java println() method to print the class property values, month, day, and year.
- Please note that to access the property values, this keyword must be preceded with the property name.
Important notes:
- This program doesn't consider the valid input range of days for Feb (1 - 28 or 29) and for those of the months with only 30 days because this is not expected by the question.
- Beside, the input year is also presumed to be a four digit number.