Java inheritance and generics
I'm trying to extend an abstract class with generics and I'm running into a problem:
abstract public class SomeClassA<S extends Stuff> {
protected ArrayList<S> array;
public SomeClassA(S s) {
// ...
}
public void someMethod() {
// Some method using the ArrayList
}
abstract public void anotherMethod() {
// ...
}
}
Now I want to extend this class with another abstract class so I could override "someMethod". I tried:
abstract public class SomeClassB<Z extends Stuff> extends SomeClassA {
public SomeClassB(Z z) {
super(z);
}
@Override public void someMethod() {
// Some method using the ArrayList
}
}
NetBeans doesn't see any problem with the constructor, but I cannot use the ArrayList from SomeClassA within the method someMethod. So I tried:
abstract public class SomeClassB<Z extends Stuff> extends SomeClassA<S extends Stuff> {
public SomeClassB(Z z) {
super(z);
}
@Override public void someMethod() {
// Some method using the ArrayList
}
}
And now it's just very odd. Everyth开发者_如何转开发ing seems to work (and I can now use the arraylist, but NetBeans says there's a "> expected" in the declaration of SomeClassB and it just won't compile. If possible, I would like:
To know how to solve this particular problem.
To have a good reference to understand generics.
To know if it's any easier in C#.
You will need to pass the generic type to the superclass also, like this:
abstract public class SomeClassB<Z extends Stuff> extends SomeClassA<Z>
Your superclass and subclass will then both use the same generic type. Generic Types are not inherited by subclasses or passed down to superclasses.
For a good reference to understand generics, check out Effective Java, 2nd Edition.
精彩评论