Qualtar Demix Qualtar Demix - 5 months ago 13
Java Question

Same method with different return types in abstract class and interface

Just extending the question..

Same method in abstract class and interface

Suppose a class implements an interface and extends an abstract class and both have the same method (name+signature), but different return types. Now when i override the method it compiles only when i make the return type same as that of the interface declaration.

Also, what would happen if the method is declared as private or final in the abstract class or the interface?

**On a side note. Mr. Einstein stuck to this question for an abominable amount of time during an interview. Is there a popular scenario where we do this or he was just showing off?

Answer

If the method in abstract class is abstract too, you will have to provide its implementation in the first concrete class it extends.Additionally, you will have to provide implementation of interface. If both the methods differ only in return type, the concrete class will have overloaded methods which differ only in return type. And we cant have overloaded methods which differ only in return type,hence the error.

interface io    
 {
   public void show();
 }

abstract class Demo
{
 abstract int show();         
}

class Test extends Demo implements io

{  void show ()     //Overloaded method based on return type, Error
   {
   }
   int show()       //Error 
   {
     return 1;
   }
   public static void main (String args[])

    {

    }


}