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

问下 inner class 里想写 static nested class 作为工具类的时候该怎么办

  •  
  •   karia · 2019-04-02 02:55:06 +08:00 · 1748 次点击
    这是一个创建于 1844 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Inner class 里不能写 static nested class,可是有些场景感觉这么封装最合适 Orz

    public class Outer {
        class Inner {
        	// static class Helper {} // error
        }
    }
    

    举个栗子

    public class BTree {
    	class Node {
    		/*static*/ class Pair {
    			final int k;
    			final double v;
    		}
    		// blabla..
    	}
    	// blabla..
    }
    
    5 条回复    2019-04-09 23:40:58 +08:00
    karia
        1
    karia  
    OP
       2019-04-02 03:40:27 +08:00
    可能应该把 Inner 写成 package-private 的顶级类了
    karia
        2
    karia  
    OP
       2019-04-02 03:44:19 +08:00
    但是 Inner 要访问 Outer 的 field 的时候非要这么拆就影响內聚
    lzdhlsc
        3
    lzdhlsc  
       2019-04-02 04:19:14 +08:00
    inner static class 如何? public static class Node...
    zealot0630
        4
    zealot0630  
       2019-04-02 09:21:28 +08:00 via Android
    static is evil。static 破坏了语言的 lexical scope,outer class 的成员明显在你的 scope 里面,你却无法访问。参考 scala 是怎么去掉 static 关键字的,一方面用 Singleton 取代了,另一方面,强制你必须放外面去
    ChanKc
        5
    ChanKc  
       2019-04-09 23:40:58 +08:00
    @zealot0630 If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration, making it a static rather than a nonstatic member class.

    来自 Effective Java 3rd Edition Item 24
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3649 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 04:18 · PVG 12:18 · LAX 21:18 · JFK 00:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.