Continuing from previous topics
How to implement multiple interface in Java?

In this Topic, lets see very interesting scenario:

How to implement common methods declaration when we have in implementing interfaces ?

Example in above interfaces: IAddition & IDivision let me declare for display (); method.

interface IAddition {             
 int add (int a, int b); 
 void display ();
} 
interface IDivision {              
  double  divide (int a, int b); 
  void display ();
}

We can have only one method with same name with same signature inside a class. Lets write one implementation for display ();

// implementing 2 interface.
class Calculator implements IAddition,  IDivision {

           @Override
           public int add ( int a, int b) {
                result a + b;
           }

           @Override
           public double divide ( int a, int b) {
                result a / b;
           }
           
           @Override
           public void display () {
                System.out.println ( " Display() for Calculator implementation. " );
           }
}

Here display(); implementation is common for both IAddition & IDivision class.

Then how do we invoke the methods.
When you invoke for the IAddition reference it will refer the declaration and takes the implementation defined in Calculator Class.

Scneario 1:

IAddition additionObj = new Calculator ();

Here,  additionObj  can call 
int add (int a, int b); void display (); 

Since the interface declares for both methods and additionObj   treats display() in Calculator class is for defined for IAddition interface

Scneario 2:

IDivision divObj= new Calculator ();

Here,  divObj  can call 
double division(int a, int b); void display (); 

Since the interface declares for both methods and  divObj treats display() in Calculator class is for defined for IAddition interface

Scenario 3:

Calculator calObj= new Calculator ();

Here, calObj can call 
int  add ( int a, int b),
double division(int a, int b);
&
void display (); 

Since the method defined in class  will have access for all the methods defined in it.

When you have same name and signature methods declared in the multiple interface which is used to implement class you can define as common methods for both interface implemented class.

Advertisements