← Java from Scratch Lesson 35 of 88 · 10 XP

The this keyword

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

this is a reference to the current object. It has three uses:

class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;           // 1. the field x, not the parameter x
        this.y = y;
    }

    Point() {
        this(0, 0);           // 2. calling another constructor
    }

    Point move(int dx, int dy) {
        x += dx; y += dy;
        return this;          // 3. return itself — then the calls can be chained
    }
}

new Point().move(1, 2).move(3, 0);   // a "fluent" interface

Task. Finish Pizza: the methods size(String) and add(String topping) — each returns this — and toString() in the format Pizza M: cheese, mushrooms (with no toppings — Pizza M: empty). The default size is M.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.