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?
We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types.
Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.
Interface types act like class types. You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type.
No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.
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;
}
}
As you can see, you're bound to use Integer
because generics don't work with primitives.
Also note, those 2 versions of the same interface are essentially 2 different interfaces now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With