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

后端 未结 5 1989
长发绾君心
长发绾君心 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: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;
      }
    
    }
    

提交回复
热议问题