5

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.

javanna
  • 59,145
  • 14
  • 144
  • 125
S..K
  • 1,944
  • 2
  • 14
  • 16

2 Answers2

8

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.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • "An inner class is a nested class that is not explicitly or implicitly declared static. [...] Member interfaces (§8.5) are always implicitly static so they are never considered to be inner classes." quote from http://java.sun.com/docs/books/jls/third_edition/html/classes.html – Zoltan Balazs Apr 08 '11 at 10:37
  • 1
    So there is no such thing as an inner class interface – Zoltan Balazs Apr 08 '11 at 10:38
  • 2
    @Zoltan: The question was **why** are there no such things? – Paŭlo Ebermann Apr 08 '11 at 10:40
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.