为什么Java只接受具有相同返回类型的重写基类方法?

Kar*_*ikk 1 c# java

我在C#的背景.我想知道为什么Java重写的基类方法需要相同的返回类型,即使我们将重写的返回类型更改为基类类型它会引发错误.任何人都可以让我知道这个的原因吗?请从下面找到代码段.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

首先,不,这在C#中不起作用 - 不是在你实际上覆盖方法时.(如果你使用它会起作用new,但是你不会覆盖.)C#比Java更严格,因为返回类型必须完全匹配...而Java允许你返回一个更具体的类型,只是没有更普遍的一个.例如,这很好:

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

public class Child extends Base {
    @Override public String getFoo() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

......但你正试图做相反的事情.

为了说明为什么这是危险的,想象一下你将Child.iterator()方法实现改为return new Test();.然后想象有人写道:

Collection collection = new Child();
ListIterator iterator = collection.iterator();
Run Code Online (Sandbox Code Playgroud)

一切看起来完全类型安全,因为Collection.iterator()声明返回ListIterator- 但返回的值既不是null也不是对a的引用ListIterator.

所以基本上,答案是"Java正在保护你不要在脚下射击.这是一件好事."