问题描述
以下代码使用Java中方法覆盖的概念。
The following code uses the concept of method overriding in 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);
}
}
}
按照惯例,方法覆盖使用超类和子类中的相同签名(带有返回类型)。在上面的代码中, SuperClass
中 getList()
方法的返回类型是列表
,在其子类中,返回类型为 ArrayList
。方法覆盖如何在这里工作?
By convention, method overriding uses the same signature (with return type) in both super class and subclass. In the above code, the return type of the getList()
method in the SuperClass
is List
and in its subclass the return type is ArrayList
. How does method overriding work here?
顺便说一下,很明显 ArrayList
是<$的实现c $ c>列出接口,但编译器在覆盖 getList()
方法时如何处理返回类型?
By the way, it's obvious that ArrayList
is an implementation of the List
interface but how does the compiler treat the return type here while overriding the getList()
method?
我应该相信这样的事情...... 被覆盖方法的返回类型被允许是被覆盖方法的返回类型的子类型。
Should I believe something like this... The return type of the overridden method is allowed to be a subtype of the overridden method's return type.
推荐答案
是。
在早期的java中并非如此,但它已被更改在Java 5.0中。
In early java that was not the case, but it was changed in Java 5.0.
此信息的来源不再可用于互联网。
The source of this information is no longer available on the interwebs.
这篇关于Java中的协变返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!