Covariant return type in Java -


the following code uses 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);         }     } } 

by convention, method overriding uses same signature (with return type) in both super class , subclass. in above code, return type of getlist() method in superclass list , in subclass return type arraylist. how method overriding work here?

by way, it's obvious arraylist implementation of list interface how compiler treat return type here while overriding getlist() method?

should believe this... the return type of overridden method allowed subtype of overridden method's return type.

yes.

in java not case, changed in java 5.0.

you cannot have 2 methods in same class signatures differ return type. until j2se 5.0 release, true class not override return type of methods inherits superclass. in tip learn new feature in j2se 5.0 allows covariant return types. means method in subclass may return object type subclass of type returned method same signature in superclass. feature removes need excessive type checking , casting.

the source of information no longer available on interwebs.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -