gpt4 book ai didi

java - Java 中的协变返回类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:46 27 4
gpt4 key购买 nike

下面的代码使用了 Java 中方法覆盖的概念。

package pkg;

import java.util.ArrayList;
import java.util.List;

abstract class SuperClass
{
abstract public List<String>getList();
}

final class SubClass extends SuperClass
{
private List<String>list=null;

@Override
public ArrayList<String> getList()
{
list=new ArrayList<String>();
list.add("A");
list.add("B");
return (ArrayList<String>) list;
}
}

final public class Main
{
public static void main(String[] args)
{
SuperClass s=new SubClass();
List<String>list=s.getList();

for(String str:list)
{
System.out.println(str);
}
}
}

按照惯例,方法覆盖在父类(super class)和子类中使用相同的签名(具有返回类型)。在上面的代码中,SuperClass中的getList()方法的返回类型是List,在它的子类中返回类型是数组列表。方法覆盖在这里如何工作?

顺便说一句,很明显 ArrayListList 接口(interface)的实现,但是编译器如何在覆盖 getList( ) 方法?

我应该相信这样的事情吗?被覆盖方法的返回类型可以是被覆盖方法返回类型的子类型。

最佳答案

是的。

在早期的 Java 中并非如此,但在 Java 5.0 中发生了变化。

You cannot have two methods in the same class with signatures that only differ by return type. Until the J2SE 5.0 release, it was also true that a class could not override the return type of the methods it inherits from a superclass. In this tip you will learn about a new feature in J2SE 5.0 that allows covariant return types. What this means is that a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. This feature removes the need for excessive type checking and casting.

此信息的来源在互联网上不再可用。

关于java - Java 中的协变返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10134571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com