Adam Lee
Adam Lee

Reputation: 25738

What does the following snippet mean?

 TestClass.this.onError(error);

I think this is the keywork in java, how can a classname follows with this? Is this a special feature of java?

Upvotes: 0

Views: 378

Answers (3)

Ruuhkis
Ruuhkis

Reputation: 1934

You can use that from inner class of class, it will refer to the outer class.

For example if you have class Cat

public class Cat {

private int age;
private Tail tail;

public Cat(int age) {
    this.age = age;
    this.tail = new Tail();
}

class Tail {

    public void wave() {
        for(int i = 0; i < Cat.this.age; i++) {
            System.out.println("*wave*");
        }
    }

}

public Tail getTail() {
    return tail;
}

/**
 * @param args
 */
public static void main(String[] args) {
    new Cat(10).getTail().wave();
}

}

Upvotes: 1

SJuan76
SJuan76

Reputation: 24780

From an inner class you are calling an instante method from the instance of TestClass that constains it.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499870

It's a way of accessing the implicit instance of an enclosing class from within an inner class. For example:

public class Test {
    
    private final String name;
    
    public Test(String name) {
        this.name = name;
    }
    
    public static void main(String[] args) {
        Test t = new Test("Jon");
        // Create an instance of NamePrinter with a reference to the new instance
        // as the enclosing instance.
        Runnable r = t.new NamePrinter();
        r.run();
    }    
    
    private class NamePrinter implements Runnable {
        @Override public void run() {
            // Use the enclosing instance's name variable
            System.out.println(Test.this.name);
        }
    }
}

See the Java Language Specification section 8.1.3 for more about inner classes and enclosing instances, and section 15.8.4 for the "qualified this" expression:

Any lexically enclosing instance (§8.1.3) can be referred to by explicitly qualifying the keyword this.

Let C be the class denoted by ClassName. Let n be an integer such that C is the n'th lexically enclosing class of the class in which the qualified this expression appears.

The value of an expression of the form ClassName.this is the n'th lexically enclosing instance of this.

The type of the expression is C.

Upvotes: 9

Related Questions