java--基本语法2

日期的例子:

 

代码
   
   
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);
}
}

这个类名就是MyDate.MyDate 这个类里面定义了3个属性,4个方法,2个构造函数。

java的类里面有3个东西,看下面:

    class 类名 {
    声明属性;
    声明构造函数;
    声明方法;
    }

 

调用:

 

代码
   
   
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()方法
}
}

 

你可能感兴趣的:(java)