Sunday, 16 March 2014

Inheritance using wild cards


Even though Integer is a sub class of Number, List<Integer> is not a sub class of List<Number>. Since List<Integer> and List<Number> are two different classes.

But Both the classes List<Number> and List<Integer> are the sub classes for List<?>.




Example 1
WildCardEx1.java
import java.util.*;
 
public class WildCardEx1{
    public static void main(String args[]){
        List<?> list1 = new ArrayList<Number>();
        List<?> list2 = new ArrayList<Integer>();
    }
}
 
 
 Similarly, List<Number>, List<Integer> are sub classes for List<? Extends Number>.

WildCardEx2.java
import java.util.*;
 
public class WildCardEx2{
    public static void main(String args[]){
        List<? extends Number> list1 = new ArrayList<Number>();
        List<? extends Number> list2 = new ArrayList<Integer>();
    }
}
 
 Similarly, List<Number>, List<Integer> are sub classes for List<? super Integer>.
 
WildCardEx3.java 
 
import java.util.*;
 
public class WildCardEx3 {
    public static void main(String args[]){
        List<? super Integer> list1 = new ArrayList<Number>();
        List<? super Integer> list2 = new ArrayList<Integer>();
    }
}
 
WildCardEx4.java  
import java.util.*;
 
public class WildCardEx4 {
    public static void main(String args[]){
       List<?> list1;
       List<? extends Number> list2;
       List<? extends Integer> list3;
       
       List<Integer> list4 = new ArrayList<Integer>();
       list1 = list2 = list3 = list4;
       
       List<Number> list5 = new ArrayList<Number>();
       list1 = list2 = list5;
           
    }
}
 
WildCardEx5.java 
import java.util.*;
 
public class WildCardEx5{
    public static void main(String args[]){
       List<?> list1;
       List<? super Integer> list2;
       List<? super Number> list3;
       
       List<Number> list4 = new ArrayList<Number>();
       list1 = list2 = list3 = list4;
       
       List<Integer> list5 = new ArrayList<Integer>();
       list1 = list2 = list5;
           
    }
}
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment