Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why interface variables need initialization?

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.

like image 614
Martin Heralecký Avatar asked Jan 03 '23 16:01

Martin Heralecký


2 Answers

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();
    }
}
like image 199
Kayaman Avatar answered Jan 11 '23 22:01

Kayaman


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();
}
like image 25
vikingsteve Avatar answered Jan 12 '23 00:01

vikingsteve