Question

I came across this example of an interface implementation which I can't my head around, with the text not having any reasoning for the the answer so hopefully someone on here can lend a hand.

Given the interface

interface Flyer{
   void takeOff();
   boolean land();
}

then suppose I have an implementation as follows

class Aeroplane implements Flyer{
   public void takeOff(){
   ...
   }
   //insert code here
       return true;
   }  
}

The code to insert that I am given is public boolean land(){ and it states that the following is INCORRECT boolean land(){

Why do I need to have the public when the interface has defined the method as package-private, surely boolean land(){ should implement the interface, or have I missed something?

Was it helpful?

Solution 2

"the interface has defined the method as package-private"

All methods declared in interfaces are public by definition. There is no way around this.

This

interface Flyer{
   void takeOff();
   boolean land();
}

is equivalent to this

interface Flyer{
   public void takeOff();
   public boolean land();
}

This is illegal:

interface Flyer{
   private void takeOff();
   private boolean land();
}

as is this:

interface Flyer{
   protected void takeOff();
   protected boolean land();
}

Neither will compile.

OTHER TIPS

Interface does not define method as a package-private. All methods declared by interface are public. You are confusing with the default access modifier. It is indeed package-private for classes but public for interfaces. So, definition:

interface Flyer{
   void takeOff();
   void land();
}

is absolutely equivalent to

interface Flyer{
   public void takeOff();
   public void land();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top