Access instance instance variables from default method in backend

Given that we now have methods defaulton interfacein Java 8, is there a way to access instance methods from the parent class in the inner (not static) class interface, for example something like this:

public class App {

    int appConst = 3;

    public interface MyInstanceInterface {

        default int myAppConst() {
            return appConst;
        }
    }
}

My is interfacenot staticand therefore he must have access to appConstthe context App.this.

This code fails with the following compilation error:

error: non-static variable appConst cannot refer to a static context

Why?

+4
source share
1 answer

The reason for this is JLS ยง8.5.1 :

(ยง9.1.1). - .

interface static. :

public class App {

    ...      

    public interface MyInterface {

        ...

    }
}

:

public class App {

    ...      

    public static interface MyInterface {

        ...

    }
}

N.B: Java 8.

+8

All Articles