Two Interfaces Program Explanation
Two Interfaces Program Explanation
interface Addition {
int add(int a, int b);
}
@Override
public int subtract(int a, int b) {
return a - b;
}
}
// Perform addition
int resultAddition = ccl.add(5, 3);
System.out.println("Addition result: " + resultAddition);
// Perform subtraction
int resultSubtraction = ccl.subtract(5, 3);
System.out.println("Subtraction result: " + resultSubtraction);
}
}
-----------------------
Explanation
1. Interfaces Definition:
o Addition Interface: This interface declares a method add that takes two integers and returns their
sum.
interface Addition {
int add(int a, int b);
}
o Subtraction Interface: This interface declares a method subtract that takes two integers and
returns their difference.
interface Subtraction {
int subtract(int a, int b);
}
2. Calculator Class:
o This class implements both Addition and Subtraction interfaces, meaning it provides concrete
implementations for the add and subtract methods.
class Calculator implements Addition, Subtraction {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int subtract(int a, int b) {
return a - b;
}
}
o The @Override annotation indicates that these methods are implementations of the methods
declared in the interfaces.
3. Main Class:
o This is the entry point of the program. The main method is where the program starts execution.
public class Main {
public static void main(String[] args) {
Calculator ccl = new Calculator();
// Perform addition
int resultAddition = ccl.add(5, 3);
System.out.println("Addition result: " + resultAddition);
// Perform subtraction
int resultSubtraction = ccl.subtract(5, 3);
System.out.println("Subtraction result: " + resultSubtraction);
}
}
o Creating an Instance: An instance of Calculator is created.
o Performing Operations: The add and subtract methods are called on the Calculator instance with
the arguments 5 and 3.
o Output: The results of the addition and subtraction are printed to the console.
In summary, this program demonstrates how to use interfaces to define methods for addition and
subtraction, and how to implement these methods in a class. The Main class then creates an
instance of the Calculator class and uses it to perform and display the results of these operations.