java中请给出一个return this的例子。

【新手可忽略不影响继续学习】(视频下载) (全部书籍)下面例子中setYear中的return this;返回了一个指向对象的指针,this.setMonth(8).setDay(20);是合法的,如果像原来的例子一样什么都不返回,就成了void.setMonth(8).setDay(20); 马克-to-win,系统就该报错了

 

class MyTestDate {
    int year;
    int month;

    MyTestDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
    }

    MyTestDate setYear(int year) {
        this.year = year;
        return this;
    }

    public MyTestDate setMonth(int month) {
        this.month = month;
        return this;
    }


    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).setMonth(8);
        System.out.println(date);
。。。。。。。。。。

详情请见:
http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner2_web.html#ReturnThis

猜你喜欢

转载自www.cnblogs.com/mark-to-win/p/9690884.html