Question
Is there a keyword to refer to the outer class from the inner class in Java?
public class OuterClass {
public void otherMethod() { }
public void doStuff(String str, InnerClass b) { }
public void method() {
doStuff("asd", new InnerClass() {
public void innerMethod() {
// Access outer class method
OuterClass.this.otherMethod();
}
});
}
}
Answer
In Java, when using anonymous inner classes, you can access the outer class's members using the syntax `OuterClassName.this`. This allows you to invoke methods and access variables defined in the outer class from within your inner class.
public class OuterClass {
public void otherMethod() { System.out.println("Outer method called"); }
public void doStuff(String str, InnerClass inner) { }
public void method() {
doStuff("example", new InnerClass() {
public void innerMethod() {
// Correctly refer to the outer class method
OuterClass.this.otherMethod(); // Calls outer method
}
});
}
}
Causes
- To access the outer class's instance methods or variables in an inner class, you need a way to specify which class's method or variable you are referring to.
Solutions
- Use the syntax `OuterClassName.this.methodName()` to call a method from the outer class.
Common Mistakes
Mistake: Forgetting to specify the outer class name, leading to a compilation error.
Solution: Always use `OuterClassName.this` to clarify which method or member you are trying to access.
Mistake: Using a non-static nested class when you intended to use a static context.
Solution: Ensure you understand the differences between static and non-static inner classes.
Helpers
- Java anonymous inner class
- Access outer class Java
- Java inner class example
- Java this keyword
- Java outer class methods