Friday, 25 December 2020

OOPS : two interfaces with same method

 I was asked this question in interview and I was not able to answer. I thought I will go in deep about this topic. So here is the question:


Question :

I have two interfaces say A and B. Both have same abstract method "test", exact same. Now I extends those two interfaces in a class. And I implement test method. And I ran the main method, which interface method is overridden here. 

Doubts came in my mind when I heard this question:

  1. If a class is to implement two abstract method, we need to implement both. But the problem here is both method have same signature, so which Interfaces method will get implemented here? 
  2. Will we have to implement same method twice?
  3. will we get compilation error saying two methods are abstract with same signature?
  4. what is I create object of class and cast it to interfaces ,then I will come to know which interfaces method is implemented here?

Solution:

code:


 

explanation :

We have two interfaces here Gift and Guess. Both have same method to implement.
And third interface is implementing these two interfaces.
Now any class implementing this third interface has to implement the the abstract methods.

I jus implemented one method and I was not able to get any error. Then casted class instance to interfaces and ran the code. I was not getting any error.

Observations :

  1. One implementation is serving for both abstract methods.
  2. Signature of both abstract method should be same otherwise compiler was giving error.
  3. hence we can have many interfaces with same signature methods and we can have same implementation for all those methods.

related links :




No comments:

Post a Comment