Skip to content

Latest commit

 

History

History
63 lines (55 loc) · 1.29 KB

File metadata and controls

63 lines (55 loc) · 1.29 KB

Disambiguation

If you are within an inner class and want to use a field from the instance it was created in but that field has the same name as a field in the inner class - like the following.

class Car {
    int speed = 0;

    class Speedometer {
        // Speed is declared here, but it is
        // a different field
        int speed = 5; 
    }
}

You can disambiguate between the fields by using the name of the containing class followed by .this.

class Car {
    int speed = 0;

    class Speedometer {
        // Speed is declared here, but it is
        // a different field
        int speed = 5; 

        void saySpeed() {
            IO.println(speed); // 5
            IO.println(this.speed); // 5
            IO.println(Car.this.speed); // 0
        }
    }
}
~class Car {
~    int speed = 0;
~
~    class Speedometer {
~        // Speed is declared here, but it is
~        // a different field
~        int speed = 5; 
~
~        void saySpeed() {
~            IO.println(speed); // 5
~            IO.println(this.speed); // 5
~            IO.println(Car.this.speed); // 0
~        }
~    }
~}
class Main {
    void main() {
        var car = new Car();
        var speedometer = car.new Speedometer();
        speedometer.saySpeed();
    }
}