If i have two interfaces having method named m() one's return type is void and others is int and i want to implement both of these two method in one class how should it be possible
-
Those methods aren't compatible; you can't implement both.Elliott Frisch– Elliott Frisch2016-04-06 12:05:05 +00:00Commented Apr 6, 2016 at 12:05
-
you'll need to (at least) change the signature of the method.Stultuske– Stultuske2016-04-06 12:06:30 +00:00Commented Apr 6, 2016 at 12:06
7 Answers
This will not be possible for the same reason as the following class will not compile.
You can't have two methods with the same name and the same parameters list.
public class Clazz {
public void m() {}
public int m() {}
}
A solution would be to have methods that return an instance of each interface using anonymous classes.
public interface One {
void m();
}
public interface Two{
int m();
}
public class Clazz {
One getOne(){
return new One(){
@Override
public void m() {
// TODO Auto-generated method stub
}
};
}
Two getTwo(){
return new Two(){
@Override
public int m() {
// TODO Auto-generated method stub
return 0;
}
};
}
}
Comments
As others have pointed out, if you have two interfaces like this
interface A {
void m();
}
interface B {
int m();
}
it is not possible for a class to implement both. Java 8's new functional interfaces give the methods names like getAsDouble (rather than just get) to avoid such problems.
If you are using Java 8, and your interfaces have only one method, you don't need to write implements at all. Instead you can do this
class MyClass {
public void voidMethod() {}
public int intMethod() { return 42; }
}
Then, an instance myClass of MyClass is not an A or a B but you can treat it as either by using method references.
A a = myClass::voidMethod;
B b = myClass::intMethod;
I don't know whether this solves your particular problem as you haven't given many details, but it's a useful thing to know.
Comments
interface ParentA {
void play();
}
interface ParentB {
int play();
}
class Child implements ParentA, ParentB {
public void play() {
System.err.println("Child ParentA");
}
//ERROR : return type is incompatible with ParentB.play()
//So added method with int return type too
public int play() {
System.err.println("Child ParentB");
}
}