Generics
If you declare a method to take ArrayList<Animal> it can take ONLY an ArrayList<Animal>, not ArrayList<Dog> .To avoid this we use generics :
ie.,Use ArrayList<? extends Animal> instead of ArrayList<Animal>
(Animal is parent class)
Note : But this is not required if user is sending arrays[],
Example :
public class generics {
public static void main(String[] args) {
ArrayList<Animal> A=new ArrayList<Animal>();
A.add(new Animal());
ArrayList<dog> B=new ArrayList<dog>();
B.add(new dog());
B.add(new dog());
System.out.println(new generics().cal(B));
System.out.println(new generics().cal(A));
}
// try ArrayList<Animal>-------instead of-------- ArrayList<? extends Animal>
public int cal( ArrayList<? extends Animal> A ){
return A.size();
}
}
class Animal{
private boolean wild;
public void set_wild(boolean wild){
this.wild=wild;
}
public boolean get_wild(){
return this.wild;
}
}
class dog extends Animal{
private StringBuffer dog_name=new StringBuffer();
public void set_dogname(String dog_name){
this.dog_name.append(dog_name);
}
}
Output (ArrayList<? extends Animal>) :
1
2
Output (ArrayList<Animal>)
Error
No comments:
Post a Comment