Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a same method exist in a class twice, through Inheritance and interfaces?

Tags:

java

interface

Here is the scenario:-

class Canine{
  public void roam(){
    System.out.println("Canine-Roam");
  }
}

public interface Pet{    
  public abstract void roam();
}


class Dog extends Canine implements Pet{

  public void roam(){
    System.out.println("Dog Roam");
  }
  public static void main(String [] args){
    Dog adog = new Dog();
    adog.roam();
  }
}

I am aware that JVM must not have any confusion in choosing which method to run, that means, which method gets over-ridden. But I am confused anyway. Why does this program compile?

like image 373
Ankit Avatar asked Dec 06 '25 09:12

Ankit


1 Answers

No - the same method cannot exist in a class twice.

An interface simply declares a requirement for a class to implement a particular method. It does not actually create that method.

So a class that acquires a method implemention through inheritance has that method defined. This (single) implementation satisfies the interface's requirements.

In your case:

  1. Dog extends Canine, so it means that the roam() method from Canine is available, and would be exposed as a method on Dog objects if not overridden.
  2. But then Dog then overrides the superclass' method with its own definition of roam(). This is allowed, and there is still just one unambiguous method called roam() on Dog - the new override.
  3. Dog implements Pet, which means it is required to have a roam() method. It does - so it's a valid implementation of this interface.
like image 89
Andrzej Doyle Avatar answered Dec 08 '25 23:12

Andrzej Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!