rocketboy
rocketboy

Reputation: 9741

Using this keyword in abstract context

I came across this pattern in some source codes:

public abstract class Foo {

    void doSomething(){
        System.out.println("...");
    }

    private class FooBar extends Foo{
        void doAnything(){
            Foo.this.doSomething();
        }
    }
}

Whats the significance of

Foo.this.doSomething();

or is it just some cargo cult practice?

Upvotes: 0

Views: 138

Answers (4)

Prabhaker A
Prabhaker A

Reputation: 8473

Foo.this refers to outer class object,where as this refers current class object.
According to java docs.It is also called Shadowing

Upvotes: 1

NPE
NPE

Reputation: 500713

Foo.this and this refer to two different objects.

Since FooBar is an inner class defined inside Foo, every instance of FooBar has an instance of Foo associated with it.

  • this refers to the FooBar instance itself;
  • Foo.this refers to the outer Foo instance.

See How can "this" of the outer class be accessed from an inner class?

That said, the Foo.this. in the example you show is redundant and can be omitted (unless both Foo and FooBar have a method called doSomething()).

Upvotes: 4

Lake
Lake

Reputation: 4092

Foo.this references outer class Foo's object instance, which is always bound in inner class's object.

You can think to Foo and FooBar as being instanced always together, when Foo is instantiated.

In your case is not necessary, but if you need to pass the Foo object instance to any method that requires it from the inner Foo.Bar, you can do it with:

// some method of some other class (OtherClass.java)
void someFunction( Foo foo )...

// ...
private class FooBar extends Foo{
    void doAnything(){
        otherClass.someFunction( Foo.this );
    }
}

Upvotes: 2

Boris Strandjev
Boris Strandjev

Reputation: 46953

In the example you give this is equivalent to calling doSomething(); directly.

However, if you declared the same method void doSomething() in the FooBar class you would use this notation to signify you call the method of the outer class not the inner.

In the latter case this.doSomething() would not suffice, this still will point to the this member variable of FooBar, that is why you specify specifically the class from which you want to call the method.

Upvotes: 2

Related Questions