return this;
}
void printO {
System, out. printlnC'i = " + i).
}
public static void main(String[] args) { Leaf x = new LeafO;
x.i ncrement().i ncrement() i ncrement().pri nt О;
}
} /* Output: i = 3 *///:-
Так как метод increment() возвращает ссылку на текущий объект посредством ключевого слова this, над одним и тем же объектом легко можно провести множество операций.
Ключевое слово this также может пригодиться для передачи текущего объекта другому методу:
//. initialization/PassingThis java
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeledО; System.out.println("Yummy");
}
}
class Peeler {
static Apple peel(Apple apple) {
// .. Снимаем кожуру
return apple; // Очищенное яблоко
}
}
class Apple {
Apple getPeeledO { return Peeler.peel(this); }
}
public class PassingThis {
public static void main(String[] args) { new Person О eat (new AppleO);
}