this关键字

this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。this的用法和其他对象引用并无不同。
 
只有当需要明确指出对当前对象的引用时,才需要使用this关键字
 
public class Leaf {
    int i = 0;

    Leaf increment() {
        i++;
        return this;
    }

    void print() {
        System.out.println("i = " + i);
    }

    public static void main(String[] args) {
        Leaf x = new Leaf();
        x.increment().increment().increment().print();
    }
}/* Output:
i = 3
*///:~

  


posted @ 2022-06-05 18:20  李廷伟  阅读(49)  评论(0)    收藏  举报