how do we access outer class this instance: eg in
Class A {
Class B {
this.helloB();
(A's this).hello()
}
}
how do we access A's this instance in Java
In general you use OuterClassName. this to refer to the enclosing instance of the outer class.
The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable name.
Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.
If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.
Just call
A.this.hello()
By prefixing this
with the class: A.this.hello()
Similarly, when you want to create an instance of B outside of A, you can use a.new B()
(where a instanceof A == true
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With