Java - 内部类构造函数 - 仅允许外部类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17190789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:15:44  来源:igfitidea点击:

Java - Inner class constructor - allowed for outer class only

javaconstructorinner-classes

提问by Krzysztof Stanis?awek

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)

(对不起,如果我的英语不好:P)

回答by LastFreeNickname

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.

有可能的。将内部类声明为public,但其构造函数为 private。通过这种方式,您只能在封闭类及其本身内部创建它,而不能从外部创建它。

回答by Suresh Atta

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

默认情况下,如果要获取内部类的实例,则需要先拥有外部类。

A inner classis 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.

参考。

回答by bNd

So make privateof inner class.

所以构成private内部类。

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

您不能合法地调用私有默认构造函数,因为它是私有的