Java中的静态内部类如何静态?

Answer: not static at all. A static inner class behaves like a normal class except that it is in the namespace of the outer class (“for packaging convenience”, as the official Java tutorial puts it).

因此,例如:

public class Outer { 
  private int x = 0; 
  static class Inner { 
    //... 
  }
}

与真正的内部(嵌套)类相反,您不需要Outer实例即可创建Inner实例:

Outer.Inner inner = new Outer.Inner();

内部实例对外部实例没有特殊知识。 内部类的行为就像顶级类一样,只需将其限定为“ Outer.Inner”即可。

Why I am writing about this?

因为令我震惊的是,我的两个同事(都是经验丰富的Java开发人员)不确定静态内部类是否与静态成员有关,因此不确定全局状态。

也许他们不使用静态内部类。

When do I use static inner classes?

我使用静态内部类

  1. 当它仅用于外部类并且独立于外部类的(私有)成员时,当它在概念上与外部类(例如Builder类)联系在一起时为了包装方便。

通常,静态内部类的可见性不是公开的。 在这种情况下,无论是在同一源文件中创建静态内部类还是顶层类都没有太大区别。 因此,第一个代码示例的替代方法是:

public class Outer { 
  // ...
}
// not really inner any more
class Inner { 
  // ... 
}

(2)的示例是一个Builder类:

public class Thing { 
  //... 
  public static class Builder { 
    // ... many withXXX methods 
    public Thing make() // ... 
  }
}

如果内部实例需要访问外部实例的(私有)成员,则内部需要是非静态的。

from: https://dev.to//erikpischel/how-static-is-a-static-inner-class-in-java-2dp7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值