Reputation: 235
In an interview there are two interfaces B and C each having the same method public m1() class A implements B and C , If class A has to implement method m1, the implemented method would be of which interface.
at that time i was also confused that which method would be called can you please advise
public interface A {
public void show();
}
public interface B {
public void show();
}
public class Test implements A, B {
public static void main(String[] args) {
A a;
B b;
Test t = new Test();
a = t;
a.show();
b = t;
b.show();
}
Upvotes: 2
Views: 1543
Reputation: 467
You will have to implement show
in the Test
class.
You will only be able to implement it once in the Test
class.
Keep in mind, the interfaces cannot, by definition, provide a default implementation of show
.
Therefore, when you instantiate the Test
class, the show
method will only have one implementation at run-time. It will be the same implementation even if the objects have 2 different parent interfaces.
Upvotes: 1
Reputation: 262474
In Java, both interfaces overlap and there is just one method. It is not possible to provide two separate implementations (or to choose which one you want). If the two interface method definitions have incompatible return types, the class cannot extend both interfaces at the same time.
So, both a.show()
and b.show()
will call the exact same method.
In C#, you can disambiguate.
Upvotes: 4