简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM