Consider the following code
class OuterClass{
class InnerClass{
int x;
int y;
void calculateX(){
x = y+z;//I want to acce
It generally shouldn't (it's a sign of a design problem), but try OuterClass.this.y
.
The best solution is to give the fields meaningful and distinguishing names. But this is not always possible...
To get a field or an outer instance you can use
OuterClass.this.y;
or if the field is static
OuterClass.y;
Note: y
is often short for this.y
(depending on where y
actually is defined)
Similarly, to call an instance method of an outer class you need.
OuterClass.this.method();
or
OuterClass.method(); // static
Note: in Java 8 you have method references which might be instance based. e.g.
list.stream().filter(OuterClass.this::predicate);
You could store a reference to itself in OuterClass
and use it from InnerClass
to access its fields, like so:
class OuterClass{
OuterClass reference = this;
...
class InnerClass {
...
void calculateX() {
reference.y; // OuterClass.y
this.y; // InnerClass.y
Just try this:
class OuterClass{
...
class InnerClass {
...
int yFromOuterClass = OuterClass.this.y;
}
}
You can try using getter method for y
class OuterClass{
class InnerClass{
int x;
int y;
void calculateX(){
x = getY() + x;
}
void printX(){
print();
}
}
int y;
int z;
InnerClass instance;
OuterClass(int y,int z){
this.y = y;
this.z = z;
instance = new InnerClass();
instance.y = 10;
instance.calculateX();
instance.printX();
}
void print(){
System.out.println("X:"+instance.x+"\nY:"+y+"\nZ:"+z+"\n");
}
public int getY() {
return y;
}
}