java nested interfaces and inner classes

2019-05-02 12:15发布

问题:

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.

回答1:

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.



回答2:

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.