yemerra
yemerra

Reputation: 1322

Inheriting a method with the same name but different return type

I can see that it doesn't work since I tried it. I just cannot explain why it have to be like that.

public int getValue() {
     return 2 * a;
}

public String getValue() {
     return "" + b * super.getValue();
}

The second method is from a class which is the child class of the class which implements the first getValue() method.

Why can't the same name be enough for overriding the method? The only argument that could come to my mind is that it would be against the "is a"-relation, because the class of the second method which is extended with A has to have the same abilities as A, and if you override the return type you break that law, right?

Upvotes: 1

Views: 2331

Answers (2)

Pshemo
Pshemo

Reputation: 124215

It is to prevent situation like this

class Base {
    public int getValue(){
        return 42;
    }
}
class Derived extends Base{
    public String getValue(){
        return "42";
    }
}

Now what should be returned here?

Base b = new Derived();
int value = b.getValue();

Because of b being Base type reference we should be able to safely assume that result of getValue will be int, but because of late-binding (dynamic-binding) getValue will execute code from Derived class so it will return String "42" not int which would cause problems.


Only situation when changing return type of overridden method is safe is when new return type extends/implements old return type:

public Fruit getValue(){
    ....    
}

can be overridden with something like

public Banana getValue(){
    ....    
}

Upvotes: 7

Boris the Spider
Boris the Spider

Reputation: 61138

Because in Java a method signature comprises it's name and parameter types. You cannot have two methods with the same signature.

Read this Oracle tutorial on defining methods.

As to why; what happens when I, for example, do:

final Object object = getValue();

Upvotes: 0

Related Questions