构造日期类MyDate类,包含年月日
时间: 2024-10-22 14:08:26 浏览: 40
创建一个名为`MyDate`的构造日期类,通常会包含私有变量分别代表年、月、日,以及相应的公共构造函数、getter和setter方法。以下是这个类的一个简单实现示例:
```java
public class MyDate {
private int year;
private int month;
private int day;
// 默认构造函数,设置年月日为当前时间
public MyDate() {
this(Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH) + 1,
Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
}
// 具体的构造函数接受年月日作为参数
public MyDate(int year, int month, int day) {
if (month < 1 || month > 12 || day < 1) {
throw new IllegalArgumentException("Invalid date");
}
this.year = year;
this.month = month;
this.day = day;
}
// Getter methods
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
// Setter methods
public void setYear(int year) {
this.year = year;
}
public void setMonth(int month) {
this.month = month;
}
public void setDay(int day) {
this.day = day;
}
// Overriding toString() method for better readability
@Override
public String toString() {
return String.format("%d-%02d-%02d", year, month, day);
}
}
```
阅读全文