Shadowing bug vs the fix
this is a reference to the object the current method or constructor is running on. You use it to tell a field from a parameter with the same name, to pass or return the current object, and (as this(...)) to call another constructor.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Person with fields name and age, a constructor that uses parameters with the same names, and a method isOlderThan(Person other) that uses this.age and other.age. Show it with two people.
Write a fluent class Text with methods add(String s), space() and upper() that each return this, and a toString() returning the built text. Build HELLO WORLD with one chain.
Write a class Node with int value and Node next, and a method Node link(Node n) that sets this.next = n and returns n. Build the list 1 -> 2 -> 3 in one chain and print it.
Explain it without notes
What does this refer to inside an instance method, and inside a constructor?
Why does name = name; in a constructor compile but not work?
Give two reasons to pass or return this, with an example of each.
Why can't static methods use this?
Expected output
buggy: null, 0
good: Rex, 3