I want to create an interface that will force all classes that implement it to define a static final integer variable:
public interface FooInterface {
static final int bar;
}
But the compiler says "Variable 'bar' might not have been initialized". Why do I have to give it a value in the interface? I want every implementation to define its own value, so it seems illogical to me that I have to put there some arbitrary number that will never be used.
You can't do that with an interface. All variables in an interface are implicitly public final static
.
You could define int getBar();
in the interface though, then all the implementing classes would need to return a value.
It would then be your responsibility to make sure that implementors are well behaved, but you can't prevent an implementation from returning different values, e.g.
public class Foo implements Bar {
public int getBar() {
return (int) System.currentTimeMillis();
}
}
You're thinking about this from the wrong angle.
A static final
cannot be overriden in an implementing class.
You probably want to do it like this:
public interface FooInterface {
int getBar();
}
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