当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: