0

Let's say I have class like this:

class Outer { 
   public void getOuterValue() { } 

   class Inner { 
       public void getInnerValue() { }
   } 
} 

I understand that I could create an object of this class as:

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

But let's suppose I am getting this object from some other method:

void someMethodSomewhere(Outer o) { 
        // How do I call getInnerValue() here using o? 
} 

Is there a way to call "getInnerValue" method using "o" in the scenario above?

Please let me know.

3
  • I tried "o.getInnerValue()" it did not work unfortunately.
    – test123
    Jun 27, 2014 at 7:53
  • @LutzHorn Nope you cant do that. Inner is a member instance that requires an instance of Outer, hence outer.new Inner, rather than new Outer.Inner()
    – maress
    Jun 27, 2014 at 7:54
  • @Lutz Horn No, it can't work! There might be an arbitrary number of objects of type Inner, so it can't even work in theory.
    – isnot2bad
    Jun 27, 2014 at 7:56

2 Answers 2

1

No. You need to have an instance of Inner to call methods on it.

An instance of the outer class is not enough (it would work the other way around: the inner class instance has a reference to the outer class instance).

2
  • I see. So, I guess, I would have to get rid of inner class and have method on outerclass.
    – test123
    Jun 27, 2014 at 7:57
  • Or pass in an instance of Inner.
    – Thilo
    Jun 27, 2014 at 7:58
1
void someMethodSomewhere(Outer o) { 
    // How do I call getInnerValue() here using o? 
} 

You can't. getInnerValue() is a method in Inner. Outer is not an Inner and does not have a reference to an Inner. When you are handed o, there is no way to navigate from that to any instance of Inner because there isn't one associated with o.

3
  • Is there a way to associate it with "o"? I guess, I could keep an instance of "Inner" in "Outer"
    – test123
    Jun 27, 2014 at 7:59
  • 1
    If o had an instance of Inner, then yes of course. That would be no different than o have an instance of a StringBuffer or an ArrayList or anything else. The code as written in the description does not include any instance of Inner belonging to or reachable from o. Jun 27, 2014 at 8:08
  • Yeah, I was hoping not to keep that instance that's why I didn't include that in the description. Thanks for the explanation!
    – test123
    Jun 27, 2014 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.