I know that it is not recommended, but why can I declare a member variable of an interface not static?
And what is the difference between a static and a not static member of an interface? I see that if I define an interface member variable as static, I can use it in the implementing class in a not-static way:
Interface:
public interface Pinuz {
final static int a;
public void method1();
}
Implementing class:
public class Test implements Pinuz {
public static void main(String[] args) {
Test t = new Test();
int b = t.a;
}
@Override
public void method1() {
// TODO Auto-generated method stub
}
}
I see only a warning asking me to use the member a in a static way.
Why can I declare a member variable of an interface not static?
It is implicitly static (and final) (which means it is static even if you omit the static keyword), as stated in the JLS:
Every field declaration in the body of an interface is implicitly
public,static, andfinal. It is permitted to redundantly specify any or all of these modifiers for such fields.
The reason for being final is that any implementation could change the value of member, if it's not defined as final. Then the member would be a part of the implementation, but as you know an interface is a pure abstraction.
The reason for being static is that the member belongs to the interface, and not an implementation instance.
Also, being static, you should just refer it with the class-name (otherwise you'd get a compiler warning), not through some reference, so int b = t.a; should be just written as int b = Test.a;
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