-1

I am new to Java Generics, and I'm currently experimenting with Generic Coding....final goal is to convert old Non-Generic legacy code to generic one...

I have defined two Classes with IS-A i.e. one is sub-class of other.

public class Parent {
    private String name;
    public Parent(String name) {
        super();
        this.name = name;
    }
}

public class Child extends Parent{
    private String address;
    public Child(String name, String address) {
        super(name);
        this.address = address;
    }
}

Now, I am trying to create a list with bounded Wildcard. and getting Compiler Error.

List<? extends Parent> myList = new ArrayList<Child>(); 
myList.add(new Parent("name")); // compiler-error
myList.add(new Child("name", "address")); // compiler-error
myList.add(new Child("name", "address")); // compiler-error

Bit confused. please help me on whats wrong with this ?

Sanjiv
  • 1,795
  • 1
  • 29
  • 45
  • ``myList.add(new Parent("name")); // compiler-error`` this doesn't work because you declared a list of Child but added a parent.. which doesn't have certain characteristics that are required to become Child (address in your case). Also, @sanbhat's answer below solves your problem. – zEro Jun 30 '13 at 06:00

2 Answers2

6

Thats because you have created ArrayList<Child>

To achieve same (that is, to create a List which can hold all subclasses of Parent) , you can simply declare it as List<Parent> myList = new ArrayList<Parent>();

List<Parent> myList = new ArrayList<Parent>(); --> new ArrayList should have generic type Parent
myList.add(new Parent("name")); // will work
myList.add(new Child("name", "address")); // will work
myList.add(new Child("name", "address")); // will work

EDIT:

To answer your other confusion, its illegal to write on a Upper bound wild card type, here's is a thread explaining why it is.

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

Here is why compilation error :

List<?> myList2 = new ArrayList<Child>(); 
myList2.add(new Child("name", "address")); // compiler-error

List<? extends Parent> myList2 = new ArrayList<Child>(); 
myList1.add(new Child("name", "address")); // compiler-error

Since we don't know what the element type of myList2/myList1 stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

On the other hand, given a List < ? >/List< ? extends Parent>, we can only call get() and make use of the result.

Sanjiv
  • 1,795
  • 1
  • 29
  • 45