Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can outer classes call methods of its inner class?

Tags:

java

scope

class

I have code establishing a server connection upon the event that a user clicks a specific button. I created an inner class to listen for the action. Within the single method I have in the inner class, I also establish that server connection mentioned earlier.

My question is, can the Socket connection only be utilized from within the "inner" class? Or, can the outer class proceed with communication with said server?


I do, however, understand that the inner class has unrestricted access to the outer class(as if it were the outer class. My question is the other way around.

like image 530
sherrellbc Avatar asked Jan 13 '23 05:01

sherrellbc


2 Answers

Create an instance like this and access what you want:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();
like image 146
Juned Ahsan Avatar answered Jan 24 '23 06:01

Juned Ahsan


All methods declared on the inner class are accessible ... whether they are declared as public or ... private.

If the inner methods are static then they can always be called by code in the outer class. You just need to qualify the method name with the inner class name.

Otherwise, the outer class code needs a reference for an instance of the inner class to call methods on it. (But that's normal.)


(If you were asking about whether an inner class could call methods on the outer class, it is a bit more complicated. Most of the above applies, but if the inner class is NOT static it can also call instance methods on its outer class via this.)

like image 28
Stephen C Avatar answered Jan 24 '23 05:01

Stephen C