karia
V2EX  ›  Java

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

  •  
  •   karia · Apr 2, 2019 · 2338 views
    This topic created in 2622 days ago, the information mentioned may be changed or developed.

    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 replies    2019-04-09 23:40:58 +08:00
    karia
        1
    karia  
    OP
       Apr 2, 2019
    可能应该把 Inner 写成 package-private 的顶级类了
    karia
        2
    karia  
    OP
       Apr 2, 2019
    但是 Inner 要访问 Outer 的 field 的时候非要这么拆就影响內聚
    lzdhlsc
        3
    lzdhlsc  
       Apr 2, 2019
    inner static class 如何? public static class Node...
    zealot0630
        4
    zealot0630  
       Apr 2, 2019 via Android
    static is evil。static 破坏了语言的 lexical scope,outer class 的成员明显在你的 scope 里面,你却无法访问。参考 scala 是怎么去掉 static 关键字的,一方面用 Singleton 取代了,另一方面,强制你必须放外面去
    ChanKc
        5
    ChanKc  
       Apr 9, 2019
    @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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2869 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 13:07 · PVG 21:07 · LAX 06:07 · JFK 09:07
    ♥ Do have faith in what you're doing.