Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acces variables from an inner class in java

I need to modify a variable from an inner class. The compiler says I need to declare the variable static, but then I can't modify it. The code is something like this:

public class Outter{
   private boolean b;

   public Outter(){  
      b = false;
      new Inner(b);
   }
}

public class Inner{
   public Inner(boolean b){
      b = true;
   }
}

Is there anything like the "extern" in C? Or any solution so I could modify the b variable? I've tried setting it to static and passing the whole Outter class as a parameter, but I keep having the same problem.

EDIT: Well the code is more like:

public class MainView{
   private boolean view;
   //JMenus,JMenuItems, JPanels.. declarations
   private JFrame frame
   MainView(){
     view = true;
     //initializations
     create_listeners();
   }
   public void create_listeners(){
      Menu.addActionListener(
        new ActionListener() { 
            public void actionPerformed(ActionEvent event){
                if(View){
                    new View2(frame);
                    View = false;
                }
            }

        }  
   );
   }
}

public class View2{
   private JButton back = new JButton("Back");
   public View2(JFrame frame){
    //initialitzatons
    create_listeners();
}
   public void create_listeners(){
          back.addActionListener(
        new ActionListener() { 
            public void actionPerformed(ActionEvent event){
                frame.remove(MainPanel);
                View = true;// HERE, i want to modify the variable
                }

        }  
    );
    }
 }

The problem is how should I modify the variable "View" from the View2 class.

Sorry for bad tabulation, I did it quick and required code translation to be understood.

like image 378
user1897262 Avatar asked Dec 20 '22 12:12

user1897262


1 Answers

The syntax is as follows, you obtain the reference to the outer class using Outter.this

public class Outter{
   private boolean b;

   class Inner{
       public Inner(boolean b){
          Outter.this.b = true;
       }
   }
}

Edit: It looks to me that you are trying to modify b just by passing a reference. In java this is not possible. Variables are passed as arguments by copy of reference variable (a reference variable is something like a pointer) or, in case of primitives, by copy.

like image 140
dkateros Avatar answered Jan 04 '23 06:01

dkateros