Java - Inner class constructor - allowed for outer class only

一个人想着一个人 提交于 2020-01-21 06:20:16

问题


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)


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/17190789/java-inner-class-constructor-allowed-for-outer-class-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!