- class MyTestDate {
- int year;
- int month;
- MyTestDate(int year, int month, int day) {
- /* 为了学习 this 的用法, 本例中, 我们故意用了两个相同的 year, 一个是全类作用范围的 (整个类中都有效马克 - to-win):int year; 另外一个是, 只有本块儿才起作用的块作用范围的 MyTestDate(int year, 这两个 year 不是一个 year, 如果把 this.year = year; 变成 year = year, 这两个 year 都成了块作用范围的那个 year, 这样全类作用范围的那个 year 等于没赋值, 还是 0, 输出结果就会变成 0/0/0, if here you use year = year;month = month; result is 0/0/0, because this.year still is 0.local variable 's scope is Less than the"this"variable's scope.
- */
- this.year = year;//this.year 指前面类范围的变量 int year.
- this.month = month;
- }
- void setYear(int year) {
- this.year = year;
- }
- void setMonth(int month) {
- this.month = month;
- }
- /* 系统见到 System.out.println, 会自动调用 toString, 初学者没必要深究 */
- public String toString() {
- return ""+ year +"/" + month ;
- }
- }
- public class Test {
- public static void main(String[] args) {
- MyTestDate date = new MyTestDate(2009, 7, 18);
- System.out.println(date);
- date.setYear(2009);
- date.setMonth(5);
- System.out.println(date);
- MyTestDate date1 = new MyTestDate(2009, 1, 1);
- System.out.println(date1);
- date1.setYear(2006);
- date1.setMonth(6);
- System.out.println(date1);
- }
- }
来源: http://www.bubuko.com/infodetail-2777568.html