Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance variables in interface

 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Why is it valid to declare instance variables in java interfaces?
Not sure if this question makes any sense....

Thanks,
 
Rob Spoor
Sheriff
Pie
Posts: 20533
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't.

Any "field" you declare in an interface will be a public static final field. In other words, a constant.

Try making it protected, it will fail because it would become protected static final, which is not allowed inside interfaces.
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob,

I wrote an example. This code compiles fine.



Please clarify?
 
Rob Spoor
Sheriff
Pie
Posts: 20533
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's what the Java compiler makes of that code:

Every field in an interface is public, static and final, even if you omit one or more of the modifiers.

Every method in an interface is public and abstract, even if you omit one or more of the modifiers.
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got It Rob.

Thanks
 
ben stone
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was asked by someone why Interface variables are made public static final by default by Java Language Designers. Could someone explain this.

Thanks
 
Rob Spoor
Sheriff
Pie
Posts: 20533
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because anything else is part of the implementation, and interfaces cannot contain any implementation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic