Galunid
Galunid

Reputation: 578

Java - class extending abstract class and implementing an interface having same methods

like in topic. Here's an example:

public abstract class Bird{
   public abstract void eat();
   public abstract void fly();
}


public interface Flyable{
    public void fly();
}

public class Test extends Bird implements Flyable{
   public void eat(){
      System.out.println("I'm eating");
   }

   // And what's now?
   public void fly(){

   }
}

And now, there is main question. What happens. Is an error being throwed, or fly is same for interface and abstract class?

Upvotes: 0

Views: 553

Answers (2)

nrainer
nrainer

Reputation: 2623

If the methods have the same signature, everything will be fine. It is also okay to have the implementation in the abstract class or to implement a method which is specified in multiple interfaces of the class.

In Java, a method is identified by its name and its parameters. Consequently, the return type of the implemented method must be compatible with all return types of all specified methods with the same identifier. The same applies to the throw clauses. If the return type or throw clauses of the implemented method are incompatible, you will get a compilation error.

This example is not working:

public interface Flyable {
  void eat();
  void fly();
}

public abstract class Bird {
  public int eat() {
    return 500;
  }

  public void fly() throws StallException {
  }
}

public class Eagle extends Bird implements Flyable {
}

Eagle.java, line 1: Exception StallException in throws clause of Bird.fly() is not compatible with Flyable.fly()

Eagle.java, line 1: The return types are incompatible for the inherited methods Flyable.eat(), Bird.eat()

Upvotes: 2

Andremoniy
Andremoniy

Reputation: 34900

Nothing happens. Just implement your logic inside fly() and be happy.

Upvotes: 2

Related Questions