开发者

Java inheritance and generics

开发者 https://www.devze.com 2023-02-23 03:56 出处:网络
I\'m trying to extend an abstract class with generics and I\'m running into a problem: abstract public class SomeClassA<S extends Stuff> {

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:

  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#.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消