The following code uses the concept of method overrides 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); } } }
By convention, method overrides use the same signature (with return type) in the superclass and subclass. In the above code, the return type of the getList()
method in SuperClass
is List
, and in its subclass, the return type is ArrayList
. How does the override method work here?
By the way, it is obvious that ArrayList
is an implementation of the List
interface, but how does the compiler consider the return type here, overriding the getList()
method?
Should I consider something like this ... The return type of an overridden method is allowed as a subtype of the return type of an overridden method.
source share