How do I access a field of an outer class, given a reference to an object of the inner class?
class Outer
{
int field;
class Inner
{
void method(Inner parameter)
{
// working on the current instance is easy :)
field = 0;
Outer.this.field = 1;
// working on another instance is hard :(
parameter.field = 2; // does not compile
parameter.Outer.this.field = 3; // does not compile
parameter.outer().field = 4; // This works...
}
// ...but I really don't want to have to write this method!
Outer outer()
{
return Outer.this;
}
}
}
I also tried Outer.parameter.field
and many other variants. Is there a syntax that does what I want?
You can access the static variable of an outer class just using the class name.
Note: just like static attributes and methods, a static inner class does not have access to members of the outer class.
The inner class can access any non-static member that has been declared in the outer class. Scope of a nested class is limited by the scope of its (outer) enclosing class. If nothing is specified, the nested class is private (default). Any class can be inherited into another class in C# (including a nested class).
Nested Classes In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class.
From outside the inner class, I believe that there's no way, given a reference to an inner class instance, to reference members of the outer class instance. From inside a non-static inner class, you can, of course, reference them using the Outer.this.*
syntax.
Think of it this way: the inner class is actually a completely separate class. It has a compiler-generated field (usually named something weird like this$0
). Within the inner class, the language allows you to reference that field using Outer.this
; however, that syntactic sugar is not available outside the inner class itself. Neither is the compiler-generated field.
How about this solution:
class Outer
{
int field;
class Inner
{
final Outer outer = Outer.this;
void method(Inner parameter)
{
// working on the current instance is easy :)
field = 0;
Outer.this.field = 1;
// working on another instance:
parameter.outer.field = 2;
}
}
}
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