Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Inner class constructor - allowed for outer class only

I have inner class in my code. I want to give public access to its instances, but only outer class should be able to create this instances, like in "private" access. Is it possible without making properly small package (or creating public interface for every such inner class)?

(Sorry if my english is bad :P)

like image 848
Krzysztof Stanisławek Avatar asked Jun 19 '13 12:06

Krzysztof Stanisławek


2 Answers

It is possible. Declare your inner class public, but its constructor private. This way you can create it only inside your enclosing class and itself, but not from outside.

like image 76
LastFreeNickname Avatar answered Sep 18 '22 15:09

LastFreeNickname


By default,If you want to get the instance of the inner class you need to have the Outer class first.

A inner class is a member of its enclosing class.

You need not to do anything for that.

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private

I hope I understood your question in right way.

Please refer.

like image 43
Suresh Atta Avatar answered Sep 19 '22 15:09

Suresh Atta