I will show you two generic generic styles. In part 1, I use the general declaration of the upper bound in the list as follows:
List<? extends Animal> totList = new ArrayList<Animal>();
But this will result in an error, as shown below, if you try to add an Animal object to the list:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method add(capture#1-of ? extends Animal) in the type List<capture#1-of ? extends Animal> is not applicable for the arguments (Animal)
at GenericsType.main(GenericsType.java:39)
But, as in Part2, if I declare a list inside a general class in the following format, there will be no errors when adding (Animal objects) or (subclass of Animal objects) to the list.
class GenericAnimal<T extends Animal>
{
List<T> genList = new ArrayList<T>();
}
Why in part2 he did not give an error and what is the difference between the two ad styles.
Code example:
1.Animal.java
public class Animal {
private String name;
private int height;
public void animalJump()
{
if(height>100)
{
System.out.println(name+" with height-"+height+" can JUMP");
}
else
System.out.println(name+" with height-"+height+" cannot jump");
}
public void setName(String name) {
this.name = name;
}
public void setHeight(int height) {
this.height = height;
}
public Animal(String name, int height) {
setName(name);
setHeight(height);
}
}
2.GenericsType.java
import java.util.*;
import Animal;
import Animal.Cannine;
import Animal.Feline;
import Animal.Feline.Cat;
import Animal.Cannine.Dog;
public class GenericsType {
public static List<? extends Animal> totList = new ArrayList<Animal>();
public static void processAllfunc1()
{
for(Animal a : totList)
{
a.animalJump();
}
}
public static void main(String args[])
{
totList.add(new Animal("Animal1",21));
processAllfunc1();
GenericAnimal<Animal> genericanimal = new GenericAnimal<Animal>();
genericanimal.genList.add(new Animal("Animal2",22));
genericanimal.genList.add(new Cat("Cat4",204));
genericanimal.processAllfunc2();
}
}
3.GenericAnimal.java
public class GenericAnimal<T extends Animal> {
public List<T> genList = new ArrayList<T>();
public void processAllfunc2() {
for (T a : genList) {
a.animalJump();
}
}
}
source
share