小编Kar*_*ikk的帖子

为什么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)

c# java

1
推荐指数
1
解决办法
102
查看次数

标签 统计

c# ×1

java ×1