日期的例子:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public
class
MyDate {
private int day; // 日
private int month; // 月
private int year; // 年
public MyDate( int day, int month, int year){
this .day = day;
this .month = month;
this .year = year;
}
public MyDate(MyDate date) {
this .day = date.day;
this .month = date.month;
this .year = date.year;
}
public int getDay() {
return day;
}
public void setDay( int day) {
this .day = day;
}
public MyDate addDays( int more_days) {
MyDate new_date = new MyDate( this );
new_date.day = new_date.day + more_days;
return new_date;
}
public void print() {
System.out.println( " MyDate: " + day + " - " + month + " - " + year);
}
}
private int day; // 日
private int month; // 月
private int year; // 年
public MyDate( int day, int month, int year){
this .day = day;
this .month = month;
this .year = year;
}
public MyDate(MyDate date) {
this .day = date.day;
this .month = date.month;
this .year = date.year;
}
public int getDay() {
return day;
}
public void setDay( int day) {
this .day = day;
}
public MyDate addDays( int more_days) {
MyDate new_date = new MyDate( this );
new_date.day = new_date.day + more_days;
return new_date;
}
public void print() {
System.out.println( " MyDate: " + day + " - " + month + " - " + year);
}
}
这个类名就是MyDate.MyDate 这个类里面定义了3个属性,4个方法,2个构造函数。
java的类里面有3个东西,看下面:
class 类名 {
声明属性;
声明构造函数;
声明方法;
}
调用:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public
class
TestMyDate {
public static void main(String[] args) {
MyDate my_birth = new MyDate( 22 , 7 , 1964 ); // 通过第一个构造函数new了一个叫my_birth的对象,并在参数里面赋值
MyDate the_next_week = my_birth.addDays( 7 ); // 这个对象调用了addDays(int more_days)的方法,赋值给the_next_week的变量
the_next_week.print(); // 调用print()方法
}
}
public static void main(String[] args) {
MyDate my_birth = new MyDate( 22 , 7 , 1964 ); // 通过第一个构造函数new了一个叫my_birth的对象,并在参数里面赋值
MyDate the_next_week = my_birth.addDays( 7 ); // 这个对象调用了addDays(int more_days)的方法,赋值给the_next_week的变量
the_next_week.print(); // 调用print()方法
}
}