An interface in Java is a blueprint that defines a set of methods that implementing classes must provide. It is primarily used to achieve abstraction, loose coupling, and multiple inheritance in Java.
Key Points: • An interface defines a contract that implementing classes must follow. • It supports abstraction by specifying what a class should do without defining how it should do it. • A class implements an interface using the implements keyword. • Java allows a class to implement multiple interfaces, enabling multiple inheritance. • Interfaces can contain abstract methods, default methods, static methods, constants, and private methods (Java 9+).
Example: Consider a Payment interface that defines a makePayment() method. Different classes such as CreditCardPayment and UPIPayment can provide their own implementations of this method.
Code Example:
interface Payment {
void makePayment();
}
class UPIPayment implements Payment {
@Override
public void makePayment() {
System.out.println("Payment made using UPI");
}
}
public class Main {
public static void main(String[] args) {
Payment payment = new UPIPayment();
payment.makePayment();
}
}Interview Tip: A concise interview answer is:
"An interface is a contract that defines a set of behaviors for implementing classes. It is used to achieve abstraction, loose coupling, and multiple inheritance in Java."