我有一个通用类 Wood:
public class Wood<A>{
public A element;
public Wood(A element)
{
this.elem = elem;
}
}
和一个接口(interface)Prec:
public interface Prec<A>{
public boolean prec(A a);
}
我想要一个新类,它获取 Wood 的所有属性并使用一些新方法对其进行扩展。这些方法需要类型 A 的对象实现 Prec 接口(interface)。因此我认为这段代码可以工作:
public class SortedWood<A extends Prec> extends Wood<A>
{
}
但我收到以下错误:
SortedWood.java:1: error: constructor Wood<A#2> cannot be applied to given types:
public class SortedWood<A extends Prec> extetends Wood<A>
required: A#1
found: no arguments
reason: actual and formal argument lists differ in length
where A#1,A#2 are type-variables:
A#1 extends Prec declared in class SortedWood
A#2 extends Object declared in class Wood
这里有什么问题,我该如何解决它?
最佳答案
来自 JLS §8.8.9:
It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.
这意味着,如果您的父类没有默认构造函数,但您的子类有,那么您就会遇到编译错误。
让我们删除泛型并像这样查看它:
public class Parent {
private int age;
public Parent(int age) {
this.age = age;
}
}
public class Child extends Parent {
public Child() {
}
}
上面的代码将无法编译,因为 Parent
中没有默认或无参数的构造函数。子类无法调用父类的构造函数,因为它不存在。
如果我们修复它,使其确实引用super
...
public class Child extends Parent {
public Child(int age) {
super(age);
}
}
...然后编译器又高兴了。
关于java - 仅适用于特定类型的通用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007993/