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

后端 未结 5 1967
长发绾君心
长发绾君心 2021-01-26 02:26

Consider the following code

class OuterClass{
    class InnerClass{
        int x;
        int y;
        void calculateX(){
            x = y+z;//I want to acce         


        
相关标签:
5条回答
  • 2021-01-26 03:12

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

    0 讨论(0)
  • 2021-01-26 03: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);
    
    0 讨论(0)
  • 2021-01-26 03:15

    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
    
    0 讨论(0)
  • 2021-01-26 03:23

    Just try this:

    class OuterClass{
    ...
        class InnerClass {
           ...
           int yFromOuterClass = OuterClass.this.y;
        }
    }
    
    0 讨论(0)
  • 2021-01-26 03:24

    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;
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题