Java - Inner class constructor - allowed for outer class only

你。 提交于 2019-12-01 03:24:14

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.

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.

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

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