test123
test123

Reputation: 14175

Accessing inner class methods on already created outer class object

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.

Upvotes: 0

Views: 52

Answers (2)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27200

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.

Upvotes: 1

Thilo
Thilo

Reputation: 262474

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).

Upvotes: 1

Related Questions