Monday, December 8, 2008

Why interface variables are public static and final

My understanding :
1) Why public : Any class or interface in any package should be able to use it. Interface is a contract not implementation.
2) Why final: As per OO design rules, attributes that are not an immutable constants should better not be publically accessible. (final means immutable)
3) why static : Static with final put the variable out of implementation. It will be treated as a constant. Remember : Interface is a contract not implementation.

2 comments:

Vivek Athalye said...

boss... u use lot of jargons ... "contract", "OO design rules", "out of implementation" ... :-s
why make it so complex??

let me give u some other reasons:

3) why static: u can not create instance of interface. and to access any class variable (here, interface variable) without creating instance, it should be declared as static.

2) why final: as its a static variable, its value is shared at all the places wherever it is used / accessed. so if 1 implementation of interface changes the value of the interface variable, it will be reflected in all other implementations as well... and let me tell u, it will be really a mess!! a strictly undesirable condition.
So it has to b a constant. hence final.

1) why public: as u can not create instance of the interface, whats the point in declaring a private variable that u can not use? because if u declare a private variable (if it allowed u to do so :P) it will be accessible only inside interface and (logically / conceptually speaking!!!) interface doesn't have any implementation.

conceptually, a class that implements an interface doesn't have parent-child (inheritance) relationship with the interface. so there is no point in declaring the variable protected.

keeping it in default access scope won't help in case the class that implements the interface is in another package. so can't use that either.

what remains is public and hence its public ;)

hope i've explained it clearly :)

btw, ever wondered what is an interface after all, at the byte code level? try to find INTERFACE in the java doc of java.lang.reflect.Modifier :D

- VNA

Tonnet said...

This explanation makes my life simple. Thanks. Updated my star XLS.