2

This question already has an answer here:

Suppose we have an interface such as

public interface anInterface
{
      public void aMethod();
}

and a class as follows:

public class aClass
{
   public void aMethod()
   {
      //bla bla bla
   }
}

Now I'm going to define another class such as Subclass that extends aClass and implements anInterface, as in:

public class Subclass extends aClass implements anInterface
{
   public void aMethod()
   {
      //do something
   }
}

What does exactly aMethod() do in Subclass? Does it implement the method in anInterface? Or does it overrides the method in aClass?

What should I do in order to make aMethod() implement the method of anInterface? Similarly, if I want it to override the method in aClass, what can I do with it?

marked as duplicate by Scant Roger, JB King, GlenH7 Nov 28 '15 at 16:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7

What does exactly aMethod() do in Subclass? Does it implement the method in anInterface? Or does it overrides the method in aClass?

It does both.

The compiler checks that Subclass fulfills its contract, being concrete: it must override all abstract methods in its hierarchy, including methods defined on interfaces. From the compiler's standpoint, an interface method and an abstract method on a regular class are the same thing: a method declaration with no definition.

The compiler sees that Subclass must have a method with the exact signature public void aMethod(). It has this method, so it satisfies the interface. This method overrides the definition in its parent class and its declaration in its parent interface.

  • That's kind of ambiguity or proble.! If one sets the return type of aMethod() in anInterface to int, and that of aMethod() in aClass to String for example, then there is no way for them to write code for aMethod() in Subclass. If they write 'public int aMethod()' in Subclass, then the compiler returns an error complaining that the return type is not compatible with aMethod() of class aClass. Conversly, if they write 'public String aMethod()' then the compiler says that the return type is not compatible with aMethod() of anInterface!!! How can one solve this problem? – Hedayat Mahdipour Nov 26 '15 at 20:18
  • @Hedayat it is not possible to have incompatible method signatures like that. The solution is lose either the supertype or superinterface declaration. – user22815 Nov 27 '15 at 3:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.