1

Basically I need to have an abstract class, that contains a field of a list that details it can hold subclasses of a certain class, and then create a concrete class that stores a specific subclass of that certain class.

Better explained in code I am sure:

public class A {
}

public class B extends A {
}

public abstract class AbsClass {
    protected List<? extends A> list;
}

public class ConClass extends AbsClass {
    list = new ArrayList<B>();
}

With the above code i get the compiler error

The method add(capture#3-of ? extends A) in the type List < capture#3-of ? extends A> is not applicable for the arguments (B)

the line where the list is instantiated.

How can I get this to work?

4
  • Regarding your compile error: you're leaving out details. This error has to do with trying to invoke the method list.add, not with your assignment. Your code won't compile for other reasons; namely the assignment occurs outside of a constructor or initializer block. Commented Mar 29, 2011 at 20:18
  • works fine for me... as it should... Commented Mar 29, 2011 at 20:25
  • @mlaw no, it doesn't. Nowhere is <A> declared! We're left to guess where it is declared. Commented Mar 29, 2011 at 20:28
  • @glow: A is a class, not a type parameter. A bit misleading since it's one character but it's a common fake class name, and it's included in the question. Commented Mar 29, 2011 at 20:31

1 Answer 1

7

Can you just type AbsClass?

public abstract class AbsClass<T extends A> {
    protected List<T> list;
}

public class ConClass extends AbsClass<B> {
    list = new ArrayList<B>();
}

Of course at that point it's not necessary to even move the instantiation to the subclass:

public abstract class AbsClass<T extends A> {
    protected List<T> list = new ArrayList<T>();
}

public class ConClass extends AbsClass<B> {
    //... other stuff ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.