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

hts6caw3  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(113)

考虑以下代码片段:

文件: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)
    }
}

我很惊讶(7)和(12)在编译时没有错误,因为它们访问的是类的私有字段。这是静态嵌套类给Java带来的特殊之处吗?

f87krz0w

f87krz0w1#

如果它是内部类或嵌套类,甚至private成员也可以被封闭类访问。

相关问题