Search code examples
javareturn-typeincompatibletypeerror

The return type is incompatible with <Interface.functionName>


I get

"Return type is incompatible with Bar.doClick()"

import some.library.Bar

public class Foo implements Bar {

   public enum Outcome {
       ONE, TWO, THREE, NEW;
   }

   public Outcome doClick() {
       return Outcome.NEW;
   }
}

Will give me the error, why? I am trying to return the right type I thought.

Bar.class contains the following lines:

    public enum Outcome {
        ONE, TWO, THREE, NEW;
    }
    Outcome doClick ();

I am told by Eclipse that if I change

public Outcome doClick() {
    return Outcome.NEW;
}

into

public Bar.Outcome doClick() {
    return Outcome.NEW;
}

I can solve the error but create a new one on my return line. I think I am really lost on a principle matter here and could use some foundational understanding.


Solution

  • In your Bar interface, Outcome is referring to the enum member you declared inside Bar. Therefore the doClick() abstract method has a return type of Bar.Outcome.

    In your Foo class, you declare another enum member also called Outcome. The method doClick you wrongly declared in Bar has a return type of Foo.Outcome. Since method signature does not take into account the return type, you effectively have this

    public Outcome doClick() {
        return Outcome.NEW;
    }
    
    public Bar.Outcome doClick() {
        return Outcome.NEW;
    }
    

    which will cause a compilation error because you have duplicate methods.

    Your doClick() method has to return a Bar.Outcome object to implement (satisfy) the Bar interface.

    public Bar.Outcome doClick() {
        return Bar.Outcome.NEW;
    }
    

    Because of shadowing

    return Outcome.NEW;
    

    was referring to Foo.Outcome.NEW which is not of type Bar.Outcome which is the expected return type.

    I don't know why you've declared two enums with the same name.