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

陌路散爱 提交于 2019-12-02 08:46:15

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

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