Java 继承和泛型
我试图用泛型扩展一个抽象类,但遇到了一个问题:
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() {
// ...
}
}
现在我想用另一个抽象类扩展这个类,这样我就可以重写“someMethod”。我尝试过:
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 没有发现构造函数有任何问题,但我无法在方法 someMethod 中使用 SomeClassA 中的 ArrayList。所以我尝试了:
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
}
}
但现在这很奇怪。一切似乎都正常(我现在可以使用数组列表,但 NetBeans 说 SomeClassB 的声明中有一个“>预期”,它只是无法编译。如果可能的话,我想:
要知道如何解决这个特定的问题。
有一个很好的参考来理解泛型。
知道它是否是 。在 C# 中更容易。
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:
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#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还需要将泛型类型传递给超类,如下所示:
然后您的超类和子类都将使用相同的泛型类型。泛型类型不会被子类继承或传递给超类。
You will need to pass the generic type to the superclass also, like this:
Your superclass and subclass will then both use the same generic type. Generic Types are not inherited by subclasses or passed down to superclasses.
要获得了解泛型的良好参考,请查看Effective Java,第二版。
For a good reference to understand generics, check out Effective Java, 2nd Edition.