• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding generics

 
Pankaj Mittal
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
public class Gen
{
public static void main(String args[])
{
Gen g = new Gen();
g.init();
}
public void init()
{
List<? extends Animal> l = new ArrayList<Animal>();
new Dog().addDog(l,"tommy"); //Line# 1
new Cat().addCat(l,"jerry"); //Line# 2

for(Animal a : l)
{
System.out.println(a);
}
}
}
class Animal
{
}
class Dog extends Animal
{
private String name;
Dog()
{
}
Dog(String name)
{
this.name = name;
}
public void addDog(List<? super Dog> l,String name)
{
l.add(new Beagle(name));
}

public void addDog2(List<?> l)
{
//l.add(new Dog()); //add method is not valid
}

public void addDog3(List<Animal> l)
{
l.add(new Dog());
}

public void addDog4(List<? extends Animal> l)
{
//l.add(new Dog());
}

public String toString()
{
return "Dog "+name;
}
}

class Beagle extends Dog
{
Beagle()
{
}
Beagle(String name)
{
this.name = name;
}
private String name;

public String toString()
{
return "Beagle Dog "+name;
}
}

class Cat extends Animal
{
Cat()
{
}
Cat(String name)
{
this.name = name;
}
private String name;

public void addCat(List<? super Cat> l,String name)
{
l.add(new Cat(name));
}

public String toString()
{
return "Cat "+name;
}
}

what is problem with Line# 1,2
They are not compiling
 
Ralph Jaus
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method addDog expects as parameter a list with objects being a super class of dog. But in #1 it gets a list that could contain for example a cat object (cat extends animal). Since cat isn't a super class of dog, such a call isn't possible.

The problem in #2 is of the same nature. Hope this helps.
 
L. Wei
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
generics is used only at the compile time. In your case, l is defined as



JVM doesn't know what you will use l to refer to.

then in the method declaration,


The method can take what ever super type of Dog List as the argument. Think about this, since l can refer to whatever child(grandchild...) class of Animal lists, it can bring List<Cat> or List<subClassOfDog> into the method. This is incorrect and will be definitely captured by the compiler.

You will say l is currently refer to an Animal List based on the definitely, but don't forget, using generics is just to prevent/avoid the scenario that pass the inconsistent/child type of collection into the method. In your scenario, JVM doesn't know the type of l!!!

The way to solve the problem is replace

[ July 27, 2008: Message edited by: David L. Wei ]
 
Pankaj Mittal
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic