Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in Interface

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

like image 926
Sandeep Avatar asked Dec 07 '09 07:12

Sandeep


1 Answers

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.

like image 175
Jon Skeet Avatar answered Oct 02 '22 20:10

Jon Skeet