13

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)

Krzysztof Stanisławek
  • 1,267
  • 4
  • 13
  • 27

3 Answers3

27

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.

LastFreeNickname
  • 1,445
  • 10
  • 17
1

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Constructor should be available only for the outer class (so can't be public), but it should be possible to use this object out of the outer (so class can't be private). – Krzysztof Stanisławek Jun 19 '13 at 12:28
0

So make private of inner class.

public class Outer {
    private class Inner {}
        public String foo() {
            return new Inner().toString(); 
        }
}

you can't legally call the private default constructor because it is private

bNd
  • 7,512
  • 7
  • 39
  • 72
  • When Inner is private, I can't use this out of Outer. I can make public interface specific for this class, but I want to avoid this solution, if the better one exists. – Krzysztof Stanisławek Jun 19 '13 at 12:23
  • It is solution of your this question `only outer class should be able to create this instances`. can you elaborate your question what do you really want!! it is not clear. – bNd Jun 19 '13 at 12:25
  • Only `Outer` object should have access to construct instances of `Inner`. Is it clear now? Sorry :) – Krzysztof Stanisławek Jun 19 '13 at 12:33