Fundamental impediments for non-static access from inner classes to outer interfaces

java, java-8, static

Solution

Maybe I misunderstood your question, but your code snippet is exactly equivalent to

interface Outer {
    public default String get() {
        return "hi";
    }
    public static class Inner {
        String got() {
            return get();
        }
    }
}

As the JLS Chapter 9.5 (Java 8) states

A member type declaration in an interface is implicitly `public` and `static`. It is permitted to redundantly specify either or both of these modifiers.

So if you did

Inner innerInstance = new Outer.Inner();
innerInstance.got();

what would `get()` be invoked on? There is no object of type `Outer` involved here.

Is there a fundamental reason for this difference between outer classes and outer interfaces?

This isn't the issue. Your class code is an example of inner classes, ie. non `static` nested class. The interface code is an example of a `static` nested class. You are comparing two different things.

The equivalent example with a `static` nested class within an enclosing class would be

class Outer {
    String get() {
        return "hei";
    }

    public static class Inner {
        String got() {
            return get(); // won't compile
        }
    }
}

where again it doesn't make sense for `get()` to work since there is no corresponding (enclosing) instance to invoke it on.

If the question, as @Radiodef put it, is

why must the class be implicitly static beyond that this is the existing spec?

then my answer is the following:

An interface, by definition, is

A point at which independent systems or diverse groups interact

An interface does not have state and it does not have behavior. It simply describes behavior. Interface members are implicitly `static` because an interface does not have state.

Problem

Example: ``` interface Outer { default String get() { return "hi"; } class Inner { String got() { return get(); } } } ``` This yields the error java: non-static method get() cannot be referenced from a static context. The inner interface/class is always static; unlike with an outer class where it's non-static unless declared static. This is how things are today and in the upcoming java 8. Is there a fundamental reason for this difference between outer classes and outer interfaces? Update: After reading @Radiodef´s comment I changed the inner interface to be an inner class. An outer class can't contain a non-static inner interface so the example was confusing. An inner class is really what I would like anyway. Update: For reference. This is perfectly legal: ``` class Outer { String get() { return "hei"; } class Inner { String got() { return get(); } } } ```

Original source