简体   繁体   English

Java继承和泛型

[英]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". 现在,我想用另一个抽象类扩展该类,以便覆盖“ 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. NetBeans认为构造函数没有任何问题,但是我无法在someMethod方法中使用SomeClassA的ArrayList。 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: 一切似乎都正常(并且我现在可以使用arraylist了,但是NetBeans表示SomeClassB的声明中有一个“>”,它不会被编译。如果可能的话,我想:

  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#. 要知道在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. 泛型类型不被子类继承或传递给超类。

为了更好地理解泛型,请参阅有效的Java,第二版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM