[英]Generic type in interface method Java
I have this method in my interface: 我的界面中有此方法:
public String getValue();
String is just for the example here, I don't want to return a String. 字符串只是这里的示例,我不想返回字符串。
And I want to put the method in classes that will return ints, chars or bools (depending on the class). 我想将该方法放在将返回int,char或bool的类中(取决于类)。 For example, I have a class Animal that implements my interface and has this method. 例如,我有一个Animal类,该类实现了我的接口并具有此方法。 I want it to return an int when this method is invoked in an animal. 我希望在动物中调用此方法时返回一个int值。 I have another class person that has this method, and when this method is invoked on a Person I want it to return a char. 我有另一个具有此方法的类人员,当在人员上调用此方法时,我希望它返回一个char。
public class Animal implements myInterface {
@Override
public int getValue() {
return 5;
}
}
public class Person implements myInterface {
@Override
public char getValue() {
return 'c';
}
}
I understand I have to do this with generics. 我知道我必须使用泛型来做到这一点。 But how exactly do I do it? 但是我该怎么做呢?
If I replace String in the interface with a generic type, like: 如果我将接口中的String替换为通用类型,例如:
public <T> T getValue();
then it says I cannot cast from int (or char) to T. 然后它说我不能从int(或char)转换为T。
What should I do? 我该怎么办? Thanks. 谢谢。
The proper way to do that is by having a generic interface: 正确的方法是具有通用接口:
public interface MyInterface<T> {
public T getValue();
}
public class Animal implements MyInterface<Integer> {
@Override
public Integer getValue() {
return 5;
}
}
However, this really reeks like an X/Y problem; 但是,这确实像X / Y问题。 not to mention that it's highly inefficient, boxing and unboxing all those primitives. 更不用说对所有这些基元进行装箱和拆箱的效率非常低。
What are you trying to achieve? 您想达到什么目的? What is your goal? 你的目标是什么?
Actually 其实
public <T> T getValue();
can be overridden by 可以被
public Character getValue()
This is weird ... it was for some backward-comparability mumbo jumbo. 这很奇怪。。。它是一些向后可比的大型超大型设备。 Don't do it. 不要这样
Usually, we say return types can be covariant, ie we can return a subtype in the overriding method. 通常,我们说返回类型可以是协变的,即我们可以在重写方法中返回子类型。 Since char
is a subtype of int
, we may expect that this should work 由于char
是int
的子类型 ,我们可以期望它应该起作用
public int getValue();
// overridden by
public char getValue()
however, java requires that if the return type is primitive, it must be identical, no covariance there. 但是,java 要求 ,如果返回类型是原始类型,则返回类型必须相同,并且那里没有协方差。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.