aspose file tools*
The moose likes Beginning Java and the fly likes Variables in Interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables in Interface" Watch "Variables in Interface" New topic
Author

Variables in Interface

Abhijith Prabhakar
Ranch Hand

Joined: Dec 29, 2006
Posts: 56
It's a know fact that all the variables in an Interface are implicity public static final.

Can anyone tell me what is the purpose behind making the variables public static final? Why can't user give his own modifer's?
Leandro Melo
Ranch Hand

Joined: Mar 27, 2004
Posts: 401
Hi Abhijith.

I'll take a shot and try make some sense out of that. The idea of implementing an interface is related to the idea of a contract that must be followed. When you choose to do that you accept its terms. Making the data members final is a way to accomplish that (you have access to the data, but you must use it how the contract dictates it). Still in this line of thought, why would you need this data to belong to your instance? You can't change it anyway... so just let it belong to the interface and be a static member. About being public, it might be about not hidding "contract clauses" (although you can make private and protected data members in nested interfaces). You either have access to the contract or not, but if you do, you should be able to see whole thing (well, at least the external "interface" of the contract ).

I hope this very general analogy is helpfull.


Leandro Melo
SCJP 1.4, SCWCD 1.4
Michael Jennings
Greenhorn

Joined: Jul 04, 2007
Posts: 20
an "interface" is intended to be just that - an interface.
now the question is, an interface to what?
ans. a class(abstraction of the object), and so the class must specify what interfaces it implements. and the developer can go ahead and use the particular interface to utilise the class. and that, in a way, explains why the methods are public.

coming to the variables(the data). would you want data to be specified as part of the interface to the class ? (what about OOP then ?)
since the interface is supposed to be consistently used by everyone, "instance data" in interfaces seems a bit odd. however, since it is allowed to specify variables in an interface(being "public static final") it surely must have been done with some purpose. the purpose being reasoned by me is to provide for constants that a method uses. and so, final(constant) and static(of the class implementing the interface) and public(part of the interface !)

eg.
interface Pythagorean{
static double PI = 3.14; // this will be public static final

double area(double radius);
}

class Circle implements Pythagorean{
// implemented here
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variables in Interface