访问嵌套静态类的私有静态成员

huangapple go评论64阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月23日 00:14:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定