1

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. Everything 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:

  1. To know how to solve this particular problem.

  2. To have a good reference to understand generics.

  3. To know if it's any easier in C#.

0

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ah, it makes so much sense now that I have the answer. Thank you very much !
2

For a good reference to understand generics, check out Effective Java, 2nd Edition.

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.