This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Generics problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics problem" Watch "Generics problem" New topic
Author

Generics problem

Dave Tong
Greenhorn

Joined: Jul 06, 2005
Posts: 10
Imagine this:

class ConcreteClass extends AbstractClass

public class Main {

public void doVector(Vector<AbstractClass> vector) {
for (AbstractClass ob : vector) {
// do Something
}
}

public Main() {
}

public static void main(String[] args) {
Main main = new Main();

Vector<ConcreteClass> vector = new Vector();
vector.add(new ConcreteClass());
main.doVector(vector);
}
}

This won't compile because vector is Vector<ConcreteClass> not Vector<AbstractClass>
even though ConcreteClass is a subclass of AbstractClass

I can get past this by casting vector to a simple untyped Vector,
although the compiler b!tches about unchecked conversions.

Alternatively I could declare my vectors as Vector<AbstractClass>
but in my application I actually have multiple different Concrete classes so that doesn't help.

Is there another solution that I'm missing?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Have you tried something like



?

This wouldn't allow you to add to the Vector, but you could iterate through it.
Dave Tong
Greenhorn

Joined: Jul 06, 2005
Posts: 10
That's exactly what I needed. Completely brilliant. Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generics problem
 
Similar Threads
java.lang.AbstractMethodError
why this abstract class containing a main method getting executed?
Code description
static and abstract methods
how do abstract classes like NumberFormat call the methods from their subclasses?