• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interface Variables  RSS feed

 
yaswanth yash
Greenhorn
Posts: 12
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do we have only public static final variables in interfaces?
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yaswanth yash wrote:Why do we have only public static final variables in interfaces?


Hello Yaswant,

Variables in interfaces are Static because, you have to access them through Interface Name only, as you cannot instantiate and Interface....

For public, you can infer the reason from the above reason... If you don't keep it public, then it's of no use, as it has to be accessed from the interface itself... And as you know Interface methods are abstract, so they cannot access those variables....

For final, you can say that, since they are public static, so there will be simultaneous access to those variables.. So you don't want them to be modified by outside source... As in that case you would have ambiguity in value of that variable...

I hope I answer your question properly...
 
AmanZeeK Verma
Greenhorn
Posts: 29
Android Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Snatched some good points from net, this might help you.

•Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.

•If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.

•An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.

So, they are public static and final variables!!!.. It belongs at implementing class level and not class's generated-object level and defines spec. of implementing class.

Hope it helps.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yaswanth yash wrote:Why do we have only public static final variables in interfaces?

Because they're meant to be constants, not variables; and many would actually argue that it's a bad thing to do because it causes API "leakage".

Winston
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you search the web for Java static import, you find that people used to think lots of public constants was a good idea, but more recently opinions have changed, so 8 years ago static import was introduced as an alternative.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!