V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
000wangxinyu000
V2EX  ›  Java

JAVA 使用内部静态类实现单例模式的一个小疑问

  •  
  •   000wangxinyu000 · 2016-11-14 21:01:24 +08:00 · 4090 次点击
    这是一个创建于 2720 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天使用静态内部类实现单例模式时,看到一个小细节。静态内部类 Inner 中 instance 居然是私有成员变量,而且在外部类 Singleton 中使用的时候居然直接引用了。我看到好多地方都这样用,而且下面代码测试也能通过。请问为什么静态内部类中的私有成员变量可以在外部类中使用?

    public class Singleton
    {
    private Singleton(){ }

    public static Singleton getInstance()  
    {  
        return Inner.instance; /*此处使用了静态内部类的私有静态成员变量?*/      
    }  
      
    //在第一次被引用时被加载  
    static class Inner  
    {  
        private/*why?*/ static Singleton instance = new Singleton();  
    }  
      
    public static void main(String args[])  
    {  
        Singleton instance = Singleton.getInstance();  
        Singleton instance2 = Singleton.getInstance();  
        System.out.println(instance == instance2);  
    }  
    

    }

    GhostFlying
        1
    GhostFlying  
       2016-11-14 21:27:11 +08:00   ❤️ 1
    static inner class 被视作 top level 的 class 的一个 member ,和 field 和 method 一样

    http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1
    000wangxinyu000
        2
    000wangxinyu000  
    OP
       2016-11-15 09:05:15 +08:00
    @GhostFlying 奥奥~明白了~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1253 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:52 · PVG 07:52 · LAX 16:52 · JFK 19:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.