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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With