I have classes A, B, C and D where B extends A, C extends A and
Look at this example and choose as per your requirement
package com.generic;
import java.util.ArrayList;
public class SuperExtendTest {
/**
* @param args
*/
public static void main(String[] args) {
}
public void test() throws Exception {
ArrayList parents=new ArrayList<>();
parents.add(new Parent());
parents.add(new Child());
//parents.add(new GrandParent()); Not allowed
ArrayList p=new ArrayList<>();
ArrayList c=new ArrayList<>();
ArrayList gp=new ArrayList<>();
testExtendP(p);
//testExtendP(c); Not allowed only super type allowed no child
testExtendP(gp);
testExtends(c);
testExtends(p);
//testExtends(gp); Not allowed because GrantParent does not extends Parent
}
/**
* This Method allowed get operations for Parent
* No add
*
*/
public void testExtends(ArrayList extends Parent> list) throws Exception {
/* list.add(new Child());
list.add(new Parent());
list.add(new GrandParent());
// can not add
*/
Child c=(Child) list.get(0);
Parent parent=list.get(0);
GrandParent gp=list.get(0);
/**
* Unsafe collection way
*/
ArrayList list2=new ArrayList();
list.addAll(list2);
}
/**
* This Method allowed add operations for Parent and it's sub types and on get it gives Object type
*
*/
public void testExtendP(ArrayList super Parent> list) throws Exception {
list.add(new Child());
list.add(new Parent());
//list.add(new GrandParent());
/*can not add because GrandParent can not be converted to Parent type
*
* The method add(capture#3-of ? super Parent) in the type ArrayList is not applicable for the arguments (GrandParent)
*
*/
Child c=(Child) list.get(0);
Parent parent=(Parent) list.get(0);
GrandParent gp=(GrandParent) list.get(0);
Object obj=list.get(0);
/**
* Unsafe collection way
*/
ArrayList list2=new ArrayList();
list.addAll(list2);
}
/**
* This Method allowed all operations for Parent and it's sub types
*
*/
public void testDirect(ArrayList list) throws Exception {
list.add(new Child());
list.add(new Parent());
//list.add(new GrandParent());
/*
* Can not add GrandParent (Normal generic rule)
*/
}
}
class GrandParent{
}
class Parent extends GrandParent{
}
class Child extends Parent{
}