[英]Can I restrict access to private fields between static nested classes in java?
If I have a class with two static
nested classes, is there any way to restrict access of private static
fields in one class from the other? 如果我有一个包含两个static
嵌套类的类,有没有办法限制一个类中的private static
字段与另一个类的访问? Example: 例:
public class Outer {
private static class Inner1 {
private static int privateInner1 = 0;
private Inner1() {
System.out.println(privateInner1 + ", " + Inner2.privateInner2); // prints "0, 1"
}
}
private static class Inner2 {
private static int privateInner2 = 1;
}
public static void main(String[] args) {
new Inner1();
}
}
Not that I actually have a use case for this in mind, I'm just curios. 并不是说我实际上有一个用例,我只是好奇。
Thanks! 谢谢!
From http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1 来自http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1
A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. 私有类成员或构造函数只能在顶级类(第7.6节)的主体内访问,该类包含成员或构造函数的声明。
You can't restrict access to the inner classes from the outer class because members, whether public or private, of inner classes can be accessed by outer classes. 您不能限制从外部类访问内部类,因为外部类可以访问内部类的成员,无论是公共类还是私有成员。 And in this scenario, the main method is part of Outer
, so it will be able to access the members of both Inner1
and Inner2
. 在这种情况下,main方法是Outer
一部分,因此它将能够访问Inner1
和Inner2
的成员。 The closest you can get to your objective is by creating an instance of an interface inside the outer class and define member variables there. 最接近目标的是通过在外部类中创建接口实例并在那里定义成员变量。 These member variables will not be accessible to the outer class. 外部类不能访问这些成员变量。 Here's an example, 这是一个例子,
private interface Example{
void doSomething();
}
private Example Inner3 = new Example(){
private int privateInner3 = 2;
public void doSomething(){
System.out.println(privateInner3);
}
}
Now in your main method, you won't be able to access Inner3.privateInner3
, but you can call Inner3.doSomething()
. 现在在main方法中,您将无法访问Inner3.privateInner3
,但您可以调用Inner3.doSomething()
。
没办法,您可以提供的最少访问权限是private
( 您已经提供 ),并且由于您尝试在同一个类中访问它们,因此您无法阻止它们访问,毕竟它们属于同一个族。
You can't. 你不能。 Inner classes are intended to be used when some functionality of the outer class is clearer when it is extracted in another class, but it is still tightly coupled with the outer class. 当外部类的某些功能在另一个类中被提取时更清晰,但它仍然与外部类紧密耦合时,将使用内部类。 So basically you should be using the inner class within the outer class to have better code separation. 所以基本上你应该使用外部类中的内部类来更好地进行代码分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.