简体   繁体   中英

nested classes - how to get variable from inner class?

class OuterClass {
    ...
    class InnerClass {
       int i;
       public void foo() {
          i = 2; 
       }
    }
}

How do I get that i value so I can use it in a method in the OuterClass?

Since variable i is not static , you need an instance of the inner class to access it. new InnerClass().i; will be sufficient to get and use it in outer class.

OuterClass.InnerClass innerObject = outerObject.new InnerClass(); By using this object u can call method. But method shoud return i value. public int foo() { i = 2; return i; }

OuterClass outer = new OuterClass();
outer.InnerClass inner = new InnerClass();
inner.foo();

Since the inner class variable i is not static, nor there is any instance of inner class being created on outer class. You would need to create an instance of outer class, get the new instance of inner class associated with it and then on that instance call the method which makes the i value changes and then read the i value. To make it more better, you can think of adding getter method on i.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM