Why does Java only accept overridden base class method with the same return type?

My background in C#. I want to know why Java overridden base class method expects same return type, even if we change the overridden return type to be of the base class type it throws an error. Can anyone let me know the reason for this? Please find the code snippet from below.

public class ListIterator
     extends Test // Test is base for ListIterator
{
}

class Collection
{
    public ListIterator iterator() throws Exception {
        return new ListIterator();
    }
}


class Child 
    extends Collection
{
   //Here the return type “Test” is the base for ListIterator, but still it 
   //throws error to mark the return type as ListIterator. If we comment the 
   //extended base class "Collection" it works as expected.

    public Test iterator() throws Exception {
        return new ListIterator();
    }
}
Jon Skeet
people
quotationmark

Firstly, no, this wouldn't work in C# - not when you're actually overriding the method. (It will work if you use new, but then you're not overriding.) C# is more strict than Java, in that the return types do have to match exactly... whereas Java allows you to return a more specific type, just not a more general one. For example, this is fine:

public class Base {
    public Object getFoo() {
        ...
    }
}

public class Child extends Base {
    @Override public String getFoo() {
        ...
    }
}

... but you're trying to do the opposite.

To show why that's dangerous, imagine that you changed your Child.iterator() method implementation to return new Test();. Then imagine someone has written:

Collection collection = new Child();
ListIterator iterator = collection.iterator();

Everything looks perfectly type-safe, because Collection.iterator() is declared to return ListIterator - but the returned value is neither null nor a reference to a ListIterator.

So basically, the answer is "Java is protecting you from shooting yourself in the foot. This is a good thing."

people

See more on this question at Stackoverflow