Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
Overv Avatar asked Aug 14 '13 08:08

Overv


1 Answers

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
  }
}
like image 106
user902383 Avatar answered Oct 03 '22 07:10

user902383