An interface in Java is a contract that defines a set of methods that implementing classes must provide. It specifies what a class should do without defining how the functionality is implemented. Interfaces are widely used to achieve abstraction, loose coupling, and multiple inheritance in Java.
Key Points: • An interface contains method declarations that implementing classes must define. • It helps achieve abstraction by separating behavior from implementation. • A class uses the implements keyword to implement an interface. • Java allows a class to implement multiple interfaces. • Interfaces promote loose coupling and make applications easier to maintain and extend. • Since Java 8, interfaces can also contain default and static methods.
Example: A payment system may support multiple payment methods such as Credit Card, UPI, and PayPal. The application can define a common Payment interface, while each payment method provides its own implementation.
Code Example:
interface Payment {
void pay(double amount);
}
class CreditCardPayment implements Payment {
@Override
public void pay(double amount) {
System.out.println("Payment made using Credit Card");
}
}
class UpiPayment implements Payment {
@Override
public void pay(double amount) {
System.out.println("Payment made using UPI");
}
}
public class Demo {
public static void main(String[] args) {
Payment payment = new UpiPayment();
payment.pay(1000);
}
}Output:
Payment made using UPI
Benefits of Interfaces:
• Supports abstraction • Enables loose coupling • Allows multiple inheritance of type • Improves flexibility and maintainability • Makes code easier to test and extend
Interview Tip: A concise interview answer is:
"An interface is a contract in Java that defines a set of methods that implementing classes must provide. It specifies what a class should do rather than how it should do it. Interfaces are commonly used to achieve abstraction, loose coupling, and multiple inheritance."