简体   繁体   中英

How to create a class with a package private constructor?

I'm working on a library where I want to return an object representing a real world object. I want to expose this class to developers to manipulate the real world object, but I don't want to allow them to construct these objects themselves.

Example

public class World {
    public static List<RealObject> getAllObjects() {
        // How to create RealObject with physicalID?
    }
}

public class RealObject {
    private int physicalID;

    public RealObject(int physicalID) {
        // Undesirable, user has no knowledge of IDs
    }

    public void setState(int state) {
        // Code using physicalID to change state
    }
}

These objects currently have no constructor and have a private id field that I set with reflection from within my library. This works perfectly, but I can't help but think there must be a better solution. Perhaps a useful constraint in my situation is that it only needs to be possible to construct this object from one other class.

Is there a better solution? And is it still possible to have the class in a separate file in that case for organizational purposes?

If you put default access level on constructor (or any other method), then can be accessed only by classes from same package.

To concretely answer the question in the title:

public class RealObject {
  RealObject(int physicalID) {
    // Package-private constructor
  }
}

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