Consider the following code
class OuterClass{
class InnerClass{
int x;
int y;
void calculateX(){
x = y+z;//I want to access the y field of the outer class
}
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");
}
}
How to access field of the outer class if there is any overlap in name?
I have tried the following:
x=super.y;
x=OuterClass.y;
and received compilation error.
Will this kind of situation ever occur in real life programs?
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);
It generally shouldn't (it's a sign of a design problem), but try OuterClass.this.y
.
Just try this:
class OuterClass{
...
class InnerClass {
...
int yFromOuterClass = OuterClass.this.y;
}
}
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
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;
}
}
来源:https://stackoverflow.com/questions/23384811/java-how-to-access-outer-class-field-if-the-fields-have-same-name