|
Accessing its enclosing instance from an inner class |
|
|
The enclosing object instance of an inner class can be accessed in Java as described in the following example:
public class EnclosingClass {
private int number = 12;
public void callInnerMethod() {
InnerClass inner = new InnerClass();
inner.printNumber();
}
class InnerClass {
public void printNumber() {
System.out.println(EnclosingClass.this.number);
}
}
public static void main(String[] args) {
EnclosingClass enclosingObject = new EnclosingClass();
enclosingObject.callInnerMethod();
}
}
|
When this code is run, 12 will be printed to the screen.
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.