实现泛型类型的接口



我有以下接口:

interface Parcel <VolumeType, WeightType> {
public VolumeType getVolume();
public WeightType getWeight();
}

我想定义一个类a来实现这个Parcel,这样从这个类返回的体积和重量都是Double类型,下面的代码是

Parcel<Double,Double> m = new A(1.0,2.0);
m.getVolume().toString()+m.getWeight().toString().equals("1.02.0");

我对泛型不熟悉,我对A定义的所有尝试都失败了。有人能告诉我一个例子,关于如何定义这样一个类?

我已经试过了:

class A implements Parcel<Double, Double> {}

错误是

Constructor A in class A cannot be applied to given types;
Parcel<Double,Double> m = new A(1.0,2.0);
^
required: no arguments
found: double,double
reason: actual and formal argument lists differ in length
2 errors

您已经添加了正确的implements子句。您得到的错误是您没有定义两个参数的构造函数:

class A implements Parcel<Double, Double> {
public A(double volume, double weight) {
...
}
你还需要实现两个接口方法:
public Double getVolume() {
...
}
public Double getWeight() {
...
}
}

最新更新