Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface method implementation

 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have a question...

Its stated that all interface methods are implicitly public.

So now if I implement this interface, does it mean that I can never override the method from the interface and make it anything other than public...

Say for example in the declaration after code below , I implement a interface and then
I dont make the method public...

1. interface Animal {
2. void eat();
3. }
4.
5. // insert code here
6.
7. public class HouseCat extends Feline {
8. public void eat() { }
9. }

--------------------------------------------------------
Declaration:

abstract class Feline implements Animal { abstract void eat(); }

Source code from Sun's practice exams
[ April 25, 2007: Message edited by: megha joshi ]
 
Steven Young
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you are correct.

All methods declared in an interface are inherently public. So any implementing classes must also declare the interface methods as public. Since you can not override a method with a more restrictive access modifier, then all method overrides in any subclasses must also be public.

This is the objective of an interface, it is a contract so that all implementing classes are guaranteed to provide public implementations for the interface methods.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Megha,

Abstract class can leave the implementation of the interface it declares that implements but can't reduce its visibility. The first concrete class must implement that interface methods (must with public visibility) + abstract class methods (which are abstract) with the same visibility or more public visibility.

In case of public visibility (as default of interface methods), no other reduced visibility is possible, obviously.


Meanwhile have a look at the some code:



Regards,
cmbhatt
[ April 25, 2007: Message edited by: Chandra Bhatt ]
 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone !! Got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic