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 :
This compiles, although I'm not sure I recommend doing things this way:
interface test {
Object get();
}
class A implements test {
int val;
public A(int x) {
val = x;
}
public Integer get() {
return val;
}
}
class B implements test {
String val;
public B(String x) {
val = x;
}
public String get() {
return val;
}
}
It's legal in Java to override a method using a return type that is a subclass of the original method's return type. This is called "covariance". It only works on return types, not on parameters. Note that to get this to compile, I had to make get
in class A
return Integer
and not int
. Also: use implements
, not extends
, when implementing an interface; and make sure that you use the correct letter case when referring to variables (Val
in your posted code does not work).
As I said, I'm not sure I recommend this, because in any code that declares something of type test
, the result of get()
is an Object
, which you will have to cast to something else to make it useful. If possible, generics should be used instead. However, it's not always possible. I would think carefully about your design before writing an interface like this. It may be that an interface isn't really what you want. However, I can't tell without more details about what you're trying to accomplish.