Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface

 
Suri Babs
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to why i shouldn't declare the private and protected variables in java interface, like the following
public interface BaseInterface{
private int i=0;
protected int j=0;
// Methods declaration
}
this is the following error i get
BaseInterface.java:3: modifier private not allowed here
private int i=0;
^
BaseInterface.java:6: modifier protected not allowed here
protected int j=0;
^
2 errors
 
billo bailey
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should as far as i understand initialize your variables in a constructor, so maybe try

i could be hopelessly wrong but think the initialization should be as above.
bill
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All declared variables in an interface are implicitly public static final. You cannot declare them as protected or private. Even if you just declare them with type alone, which would normally be package-private the compiler will see to it that they are actually public static final.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An interface cannot declare member variables.
This is an untrue statement, but is the general case. An interface can only declare member variable when they are initialized, public, and final (note that if you do not explicitly make them final the compiler will do so for you). So you can say:

They cannot be private becase there is no class to access them; subclasses cannot access private members. Likewise, they cannot be protected becasus an interface has no subclasses--just implementers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic