Interfaces in Java
An interface in Java is a reference type that is similar to a class. It is a collection of abstract methods. Interfaces may also contain constants, default methods, and static methods. Classes implement interfaces.
Declaration of Interface:
An interface is declared using the interface keyword. It can include method signatures without implementation.
public interface MyInterface {
// Abstract method signature
void myMethod();
// Another abstract method signature
int calculate(int a, int b);
}
Implementation of Interface:
To use an interface, a class must implement it using the implements keyword.
The class must provide implementations for all the methods declared in the interface.
public class MyClass implements MyInterface {
// Implementation of myMethod
public void myMethod() {
System.out.println("Executing myMethod");
}
// Implementation of calculate
public int calculate(int a, int b) {
return a + b;
}
}
Using Interface in Main Class:
Now, let's use the interface and the implementing class in the main class.
public class Main {
public static void main(String[] args) {
MyInterface myObject = new MyClass();
// Call the implemented methods
myObject.myMethod();
int result = myObject.calculate(5, 3);
System.out.println("Result: " + result);
}
}
Note:
Interfaces provide a way to achieve multiple inheritances in Java and support abstraction. Classes can implement multiple interfaces, allowing them to inherit the abstract methods from each interface.