Command Palette

Search for a command to run...

Back to the lesson: Topic 4.4 — The this Keyword
Core Java · Example 2 of 3

Returning this for a fluent API

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.

01

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.

02

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.

03

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

01

What does this refer to inside an instance method, and inside a constructor?

02

Why does name = name; in a constructor compile but not work?

03

Give two reasons to pass or return this, with an example of each.

04

Why can't static methods use this?

Returning this for a fluent API
Sign in to run this example in your browser.

Expected output

tea samosa samosa = 45
same object? true
tea samosa samosa water = 55