Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.2 Constructors — the this keyword

Lesson

this: the object being built

Inside a constructor (or method), this refers to the current object. It is most useful when a parameter has the same name as a field: this.name means the field, while plain name means the parameter. This lets you use natural names for both.


Worked example

class Dog {
    String name;

    Dog(String name) {        // parameter is also called name
        this.name = name;     // this.name = the field; name = the parameter
    }
}

Dog d = new Dog("Rex");   // d.name is Rex

▶ Try it: the constructor uses this.name = name. Run this, then change the name passed to new Dog(...) and re-run.



What does this refer to?


In Dog(String name) { this.name = name; }, why write this.name?


In this.name = name;, click the part that refers to the field.


True or false?


Type exactly what this program prints.

class Cat {
    String name;
    Cat(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Cat c = new Cat("Tom");
        System.out.println(c.name);
    }
}