Reputation: 1
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
Upvotes: 0
Views: 552
Reputation: 4218
You cannot not do this.
In Java the return type of methods does not allow to make those methods different
Upvotes: 1
Reputation: 274
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");
}
}
Upvotes: 0
Reputation: 37645
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.
Upvotes: 1
Reputation: 29
You cannot not do this.
In java the return type of a method doesn't allow to make those method diferrents if you want to do this make sure pass dummy argument in second interface w
Upvotes: 0
Reputation: 21975
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;
}
};
}
}
Upvotes: 3
Reputation: 6077
It is possible. If the methods take different arguments, then it is possible to implement them both.
eg:
interface A{
void m();
}
interface B{
int m(int a);
}
class C implements A,B{
...
}
Upvotes: 0
Reputation: 3836
how should it be possible
it is not possible, because return type is not a part of method signature in Java and compiler will produce error.
You should use different method names like mVoid()
and mInt()
(or add method parameters to make signatures differ from each other)
Upvotes: 1