3.2封装的日期类

public class MyDate //共有类,与源文件同名
{
private int year,month,day; //私有成员变量
private static int thisYear; //私有静态成员变量
static //静态成员变量初始化
{
thisYear=2012;
}
public MyDate(int year,int month,int day) //构造函数,指定日期
{
this.set(year,month,day); //调用本类中当前的成员变量
}
public MyDate() //无参构造方法。默认指定日期
{
this(1970,1,1); //调用本类中已审名的其他构造函数
}
public MyDate(MyDate d) //重载函数
{
this.set(d);
}
public void set(int year,int month,int day) //设置日期值
{
this.year=year; //this指当前的成员变量
this.month=(month>=1&&month<=12)?month:1; //判断是否满在指定的范围内
this.day=(day>=1&&day<=31)?day:1;
}
public void set(MyDate d) //函数的重载
{
set(d.year,d.month,d.day); //调用同名成员函数,不能使用this()
}
public int getYear() //获得年份
{
return this.year;
}
public int getMonth()
{
return this.month;
}
public int getDay(){
return this.day;
}
public String toString(){ //返回中文日期字符串
return year+"年"+String.format("%02d",month)+"月"+String.format("%02d",day)+"日";
}
public static int getThisYear() //静态方法获得年份
{
return thisYear;
}
public static boolean isLeapYear(int year)
{
return year%400==0||year%100!=0&&year%4==0; //判断是否闰年
}
public boolean isLeapYear() //函数的重载,判断是否闰年
{
return isLeapYear(this.year);
}
public boolean equals(MyDate d) //比较当前日期值是否与d相等
{
return this==d||d!=null&&this.year==d.year&& this.month==d.month &&this.day==d.day;
}
public static int daysOfMonth(int year,int month)
{
switch(month) //计算每月的天数
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return MyDate.isLeapYear(year)?29:28;
default: return 0;
}
}
public int daysofMonth() //返回当月天数
{
return daysOfMonth(this.year,this.month);
}
public void tomorrow() //当前日期改为后一天
{
this.day++; //改变this指针引用的实例值
if(this.day>this.daysofMonth())
{
this.day=1;
this.month++;
if(this.month>12)
{
this.month=1;
this.year++;
}
}
}
public MyDate yestoday() //返回当前日期的前一天日期
{
MyDate date=new MyDate(this);
date.day--;
if(date.day==0)
{
date.month--;
if(date.month==0)
{
date.month=12;
date.year--;
}
date.day=daysOfMonth(date.year,date.month); //拷贝构造方法
}
return date;
}
}
class MyDate_ex //当前包中的其他类
{
public static void main(String args[])
{
System.out.println("今年是"+MyDate.getThisYear()+",闰年?"+MyDate.isLeapYear(MyDate.getThisYear()));
MyDate d1=new MyDate(2012,12,31);
MyDate d2=new MyDate(d1);
System.out.println("d1: "+d1+",d2: "+d2+",d1==d2? "+(d1==d2)+", d1.equals(d2)? "+d1.equals(d2));
System.out.print(d1+"的明天是 ");
d1.tomorrow();
System.out.println(d1+" "+d1+"的昨天是 "+(d2=d1.yestoday()));
}
}

原文地址:https://www.cnblogs.com/houjinming/p/6797272.html