英文:
Accessing the private static members of nested static classes
问题
(7) and (12)编译时没有错误,因为它们访问的是同一个外部类中的私有成员,这在Java中是允许的。这是因为静态嵌套类(如(7)中的IBiLink
和(12)中的MyLinkedList.str
)可以访问其外部类(ListPool
)的私有成员,就好像它们属于外部类一样。这是Java语言中的一种访问权限规则,允许嵌套类访问其外部类的私有成员。
英文:
Consider the following code snippet:
File: ListPool.java
package smc;
import smc.ListPool.MyLinkedList;
public class ListPool { // (1) Top-level class
public static class MyLinkedList { // (2) Static member class
private static String str = "test"; // (2')
private interface ILink { } // (3) Static member interface
public static class BiNode // (4) Static member class
implements IBiLink {
public static void printSimpleName() { // (5) Static method
System.out.println(BiNode.class.getSimpleName());
}
public void printName() { // (6) Instance method
System.out.println(this.getClass().getName());
}
} // end BiNode
} // end MyLinkedList
interface IBiLink
extends MyLinkedList.ILink { // (7) Static member interface
// private static class Traversal { } // (8) Compile-time error!
// Can only be public.
class BiTraversal { } // (9) Class is public and static
} // end IBiLink
public class SortedList { // (10) Non-static member class
private static class SortCriteria {} // (11) Static member class
}
public static void main(String[] args) {
String test = MyLinkedList.str; // (12)
}
}
I'm surprised that (7) and (12) are compiled without error as they are accessing the private field of a class. Is this something special that static nested classes bring to Java?
答案1
得分: 0
如果它是一个内部或嵌套类,即使 private
成员也可以被封闭类访问。
英文:
If it's an inner or nested class, even the private
members are accessible to the enclosing class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论