The this Keyword in Java - Quiz

Total: 4 questions

1. 

What is the this keyword in Java and where is it available?

this is a reference to the current object — the instance whose method or constructor is running right now. Inside any non-static method this is available automatically: the compiler passes the reference implicitly, so reading a field as width is just shorthand for this.width. A static method, a static initializer block and main have no this at all, because there is no object; the compiler reports non-static variable this cannot be referenced from a static context.

2. 

Why do you need this when a constructor or setter parameter has the same name as a field?

The parameter shadows the field: inside such a method the simple name width refers to the parameter, not to the field of the object. To reach the field you write this.width = width; — the left side is the field, the right side is the parameter. If you forget this and write width = width;, the code still compiles but assigns the parameter to itself, leaving the field at its default value (0.0 for a double), and the bug only shows up at run time. When the parameters have different names (w, h, d) there is no shadowing and this is not required.

3. 

What does a this(...) call do and what rules apply to constructor chaining?

this(...) invokes another constructor of the same class. It removes duplication: all initialization logic lives in one "main" constructor, while the others supply default values and delegate to it — a technique known as constructor chaining. The rules are: this(...) must be the first statement of the constructor; a single constructor cannot call both this(...) and super(...); the chain must not form a loop, otherwise the compiler reports recursive constructor invocation; and you cannot invoke a constructor from an ordinary method. Since Java 25, flexible constructor bodies (JEP 513) allow a prologue before this(...) as long as it does not touch the instance under construction.

4. 

Besides resolving name clashes, where else is this used?

this is used to pass the object itself to another method, for example to register it with another class (bus.subscribe(this)), and to return the current object from a method (return this;) — the idea builders and fluent APIs rely on, chaining calls one after another. Inside a lambda expression this refers to the enclosing class instance where the lambda is written, because a lambda has no this of its own; an anonymous class behaves differently, since there this refers to the anonymous class instance itself.

Page 1 of 1