Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

this — current instance

this — current instance: this denotes the current instance in an instance method or constructor and disambiguates fields from same-named parameters.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

this

this denotes the current instance in an instance method or constructor and disambiguates fields from same-named parameters.

Use this.field for shadowed names, this(...) to delegate to another constructor as the first statement, and Outer.this from an inner class.

this is unavailable in a static context; a lambda retains the enclosing object’s this, whereas an anonymous class has its own this.

this(...) and super(...) invocations are mutually exclusive in one constructor, and a constructor-delegation cycle is a compile-time error.

The no-argument constructor delegates through this(7), this.value stores the field, and Box.this lets View read and print 7.

Examples

public class Main {
    static class Box {
        private final int value;
        Box() { this(7); }
        Box(int value) { this.value = value; }
        class View {
            int value() { return Box.this.value; }
        }
    }

    public static void main(String[] args) {
        Box box = new Box();
        System.out.println(box.new View().value());
    }
}

Result

7

The no-argument constructor delegates through this(7), this.value stores the field, and Box.this lets View read and print 7.

Sources