• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why memebrs of an interface are public?

 
Nancy Antony
Ranch Hand
Posts: 145
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

Why all members of an interface are public?

why methods in interface are not static whereas data members are public static and final?

Nancy
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nancy Antony:
Why all members of an interface are public?


An interface defines a contract with the outside world (i.e. other classes or code). As such, it only makes sense for its members to be public. For example, if the java.util.List interface had a method "manipulate()" that was marked as private, what good would it do? I wouldn't be able to access it. So it makes no sense to have an interface define (oe tell me about) a method I cannot use.

If I want to define some default implementation or some behavior or value that only List implementations have access to, I can to that in an Abstract class. So my hierarchy would be FancyList (concrete class) --> AbstractList (abstract class) --> List (interface)

Originally posted by Nancy Antony:
Why methods in interface are not static whereas data members are public static and final?


Again, anything declared in an interface must be public. As for the static final part, that's because again, a list defines a public contract. So it is defining a constant value. And this contract must be enforceable at compile time. The technical reason why they are final is because they are not inherited by extension.

If I want a variable or value to not be final, I should follow good Object Oriented Programming principles, and encapsulate such by defining a getter in my interface: getFoo(); Then each implementation would determine how Foo is determined.
[ September 01, 2008: Message edited by: Mark Vedder ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic