Java - How to access Outer class field if the fields have same name

ⅰ亾dé卋堺 提交于 2019-12-20 07:22:20

问题


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?


回答1:


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);



回答2:


It generally shouldn't (it's a sign of a design problem), but try OuterClass.this.y.




回答3:


Just try this:

class OuterClass{
...
    class InnerClass {
       ...
       int yFromOuterClass = OuterClass.this.y;
    }
}



回答4:


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



回答5:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!