Given that we now have default
methods on an interface
in Java 8, is there any way that we can access instance methods from a parent class in a inner (non static
) interface
, for example something like this:
public class App {
int appConst = 3;
public interface MyInstanceInterface {
default int myAppConst() {
return appConst;
}
}
}
My interface
is not static
and therefore it should be able to access appConst
in the App.this
context.
This code fails with the following compile error:
error: non-static variable appConst cannot be referenced from a static context
Why?
Because variables used inside a default method of an interface have access only to the variables defined inside the interface. Remember variables defined inside an interface are public,static and final and they must be initialized. within calling class.. You can only access instance variable inside "Bar" class by overriding default method.
Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn't make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.
Learn Interface variables in Java with example and Uses. You know that an interface can contains methods in java, similarly, an interface can contains variables like int, float and string too. In an interface, variables are static and final by default. All variables in an interface in java should have only public access modifier.
You can only access instance variable inside "Bar" class by overriding default method. Like so, public class Bar implements Foo { int BAZ = 10; @Override public int getBazModified () { return BAZ * 2; } }
The reason for this is JLS §8.5.1:
A member interface is implicitly static (§9.1.1). It is permitted for the declaration of a member interface to redundantly specify the static modifier.
An inner interface
can never be non-static
. The declaration:
public class App {
...
public interface MyInterface {
...
}
}
Is exactly equivalent to:
public class App {
...
public static interface MyInterface {
...
}
}
N.B: this has always been the case, and merely remains unchanged in Java 8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With