简体   繁体   中英

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.

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, eg

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();
}

You can't do that. An interface can only force the classes that implement it to implement methods.

A static variable defined in the interface belongs to the interface. It doesn't force implementing classes to declare the same variable.

Every variables in an interface is static and final. final variables must be initialized on the first line or in the constructor. Because an interface doesn't have a constructor you must initialize final variable on the first line.

因为它们是最终的,所以最终变量需要初始化。

In a normal class, we have the option to define it like that and initialize its value in static initializer block:

public class FooClass {
    static final int bar;

    static {
        bar = 5;
    }
}

In case of an interface, static initialization block is not allowed that's why Java requires it to be set to a value at declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM