Variables in Interface

2019-01-19 13:17发布

问题:

Why is that a variable used in an Interface is PUBLIC STATIC FINAL? Why "static" in particular?

回答1:

A field declared in an interface can only be a constant anyway, so why would it depend on which instance you use to access it?

Putting fields in interfaces is often poor style anyway these days. The interface is meant to reflect the capabilities of classes that implement it - which is completely orthogonal to the idea of a constant. It's certainly a nasty idea to use an interface just to declare a bunch of constants. I do occasionally find it useful to make the interface type expose constants which are simple implementations - so a filtering interface might have "ALLOW_ALL" and "ALLOW_NONE" fields, for example.

I suppose you could conceive of a scenario where implementing an interface did actually add an instance field to your class - but that would break encapsulation not only in terms of it being implicitly public, but also by specifying part of the implementation instead of the API.



回答2:

Because you can not instantiate an interface. Also there cannot be any method body to use a non-static non-final variable.



回答3:

Why wouldn't it be static?

It's a constant associated with the interface, rather than with any particular instance of it.



回答4:

The main reason I guess is implementation detail of the VM/language.

If an interface is not allowed to have non-static variables, there's no need to allocate memory for the interface during the creation of the class. There's also no need for special naming/renaming mechanisms in case you inherit variables with the same name. The only thing you need is some table to call the correct functions when the interface is used.

In short - it makes the live of the language / VM maintainer easier. If you really want to take a look at multiple inheritance and its pitfalls and traps, read Object Oriented Software Construction by Bertrand Meyer (2nd Edition). Then you understand why the interface needs to be so simple (and yet archives most of the things multiple inheritance does).



回答5:

An interface is a contract that defines the interaction between objects.

This interaction is defined by the exposed methods, not by the variables. Variables would only describe the internal working, not the interaction.

Note that variables should never be used for interaction. According to the OOP principle of encapsulation, it would be a crime to let 1 class access a variable of another class directly.

Constants (e.g.Math.PI) are the only acceptable exception. Since constants are the only kind of variables that can be accessed directly by other classes without violating the principle of encapsulation, all variables in an interface are treated as public static final variables (i.e. constants)