Covariant return type in Java
<p>The following code uses the concept of method overriding in Java.</p>

<pre><code>package pkg;

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

abstract class SuperClass
{
    abstract public List&lt;String&gt;getList();
}

final class SubClass extends SuperClass
{
    private List&lt;String&gt;list=null;

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

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

        for(String str:list)
        {
            System.out.println(str);
        }
    }
}
</code></pre>

<p>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 <code>getList()</code> method in the <code>SuperClass</code> is <code>List</code> and in its subclass the return type is <code>ArrayList</code>. How does method overriding work here?</p>

<p>By the way, it's obvious that <code>ArrayList</code> is an implementation of the <code>List</code> interface but how does the compiler treat the return type here while overriding the <code>getList()</code> method?</p>

<p>Should I believe something like this... <em>The return type of the overridden method is allowed to be a subtype of the overridden method's return type.</em></p>
