java nested interfaces and inner classes

2019-05-02 11:42发布

Why can't a java nested Interface be non-static ? And why can't an inner class contain static non final members ?

I came across the questions while going through Gosling and haven't been able to figure out the answer yet.

2条回答
Juvenile、少年°
2楼-- · 2019-05-02 12:40

I'm not sure why you can't have static non final members in an inner class but since static members aren't bound to any particular object instance it makes no difference whether it is in the inner or outer class.

E.g.

class OuterClass {

  private static int staticMember;

  class InnerClass {

    void incStatic() {
      staticMember++;
    }

  }

}

You can access the static member from the inner class as if it were within the inner class.

查看更多
Summer. ? 凉城
3楼-- · 2019-05-02 12:41

If an nested class is non-static (i.e. an inner class), this means that each instance of it is bound to an instance of the outer class. As an interface has no instances of its own, it seems to not be useful for the implementing classes to be bound to an outer object, so having it static by default seems reasonable.

查看更多
登录 后发表回答