你不能简单地向你的编译器承诺一个方法将存在于所有派生类中。你必须让它存在。你必须定义它。使用继承或接口来实现。
选项1继承
定义与一个抽象方法getInt()
一个抽象基类。所有非抽象儿童必须执行getInt()
。
public abstract class DataType() {
public abstract int getInt();
}
这个类的儿童是这样的:
public class MyDataType() extends DataType {
public int getInt() {
return 3;
}
}
选项2接口
定义的接口与方法getInt()
。所有实现该接口的类都必须定义一个方法getInt()
。顺便说一句,接口名称通常是形容词。
public interface DataTypeable {
public int getInt();
}
此接口的实现应该是这样的:
public class MyDataType() implements DataTypeable {
public int getInt() {
return 5;
}
}
现在你Utility
类可以使用基类或接口这样的(与DataTypeable
取代DataType
,如果你去的接口路径:
public class Utility {
private DataType d;
public Utility(DataType d) {
this.d = d;
}
public int getValue() {
return d.getInt();
}
}
选项3.泛型加上其他选项之一
为了实际回答问题,下面介绍如何强制它使用泛型。
public class Utility <T extends DataType> { // or <T implements DataTypeable>
private T d;
public Utility(T d) {
this.d = d;
}
public int getValue() {
return d.getInt();
}
}
然而,在这种情况下DataType
必须是上面提到的其他选项之一。这里使用泛型是没有意义的。
你在'DataType'中有'getInt()'方法吗? – dguay
当前没有DataType类。由于它是通用的,用户将在其代码中定义它。这个工具类在库中。 –
如果还没有方法,并且你希望用户在他的代码中实现它,这会创建'DataType'作为接口,那么用户应该实现它,否则编译器会一直抱怨 – Salah