本文介绍了接口(两种方法,根据类的不同返回类型)Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何扩展接口的类都必须实现在接口中声明的方法.不知道这是否可能,但是我想做的是以下事情:
Any class that extends an interface must implement the methods declared in the interface. Not sure if this is possible but what I want to do is the following :
interface test {
____ get();
}
class A extends test {
int val;
A(int x) {
val = x;
}
int get() {
return Val;
}
class B extends test {
String val;
B(String x) {
val = x;
}
String get() {
return Val;
}
是否有一个方法签名可以返回两种不同的数据类型?
Is it possible to have a method signature that is able to return two different data types?
推荐答案
不是完全一样,但是您可以使用泛型类型参数来接近它.
Not exactly like that but you can get close with a generic type parameter.
interface Test<T> {
T get();
}
class A implements Test<Integer> {
int val;
A(int x) {
val = x;
}
@Override
public Integer get() {
return val;
}
}
class B implements Test<String> {
String val;
B(String x) {
val = x;
}
@Override
public String get() {
return val;
}
}
如您所见,您必须使用Integer
,因为泛型不适用于原语.
As you can see, you're bound to use Integer
because generics don't work with primitives.
还要注意,同一接口的这两个版本现在基本上是2个不同的接口.
Also note, those 2 versions of the same interface are essentially 2 different interfaces now.
这篇关于接口(两种方法,根据类的不同返回类型)Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!