使类仅可从特定类实例化 [英] make class only instantiable from specific class
问题描述
假设我有3个班级 class1
, class2
和 class3
.
Let's say I have 3 classes
class1
, class2
and class3
.
如何让 class1
只能由 class2
( class1 object = new class1()
)实例化,而不能由class3实例化或其他任何班级?
How can I have it that class1
can only get instantiated by class2
(class1 object = new class1()
) but not by class3 or any other class?
我认为它应该与修饰符一起使用,但是我不确定.
I think it should work with modifiers but I am not sure.
推荐答案
我想将您的类重命名为 Friend
, Shy
和 Stranger
. Friend
应该可以创建 Shy
,但是 Stranger
应该不能.
I want to rename your classes to Friend
, Shy
and Stranger
. The Friend
should be able to create Shy
, but Stranger
should not be able to.
此代码将编译:
package com.sandbox;
public class Friend {
public void createShy() {
Shy shy = new Shy();
}
private static class Shy {
}
}
但是此代码不会:
package com.sandbox;
public class Stranger {
public void createShy() {
Friend.Shy shy = new Friend.Shy();
}
}
此外,如果我们创建一个名为 FriendsChild
的新类,则该不会进行编译:
In addition, if we create a new class called FriendsChild
, this won't compile either:
package com.sandbox;
public class FriendsChild extends Friend {
public void childCreateShy() {
Shy shy = new Shy();
}
}
这种命名约定在您考虑时是有意义的.仅仅因为我是某人的朋友,并不意味着我的孩子认识他们.
And this naming convention makes sense when you think about it. Just because I'm a friend of someone doesn't mean my child knows them.
请注意,所有这些类都在同一个程序包中.据我了解,这是您正在寻找的方案.
Notice that all these classes are in the same package. As far as I can understand, this is the scenario you're looking for.
这篇关于使类仅可从特定类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!