In Java, an interface is like a contract. It defines what a class should do, not how it does it. If a class says it implements an interface, it must follow the rules — meaning it must provide the methods declared by the interface.
This tutorial shows a real-world example — a payment system with options like Credit Card, Debit Card, and UPI.
✅ What is an Interface?
- An interface defines methods without implementation.
- Classes that implement the interface must define those methods.
- From Java 8, interfaces can also include:
default
methods (with body)static
methods
🧾 Payment Interface
public interface Payment {
int PAYMENT_SECRET_CODE = 0;
void makePayment(double amount);
default boolean isValidAmount(double amount) {
return amount >= 1;
}
}
📦 Implementing Classes
public class CreditCardPayment implements Payment {
public void makePayment(double amount) {
System.out.println("Payment completed using credit card");
}
}
public class DebitCardPayment implements Payment {
public void makePayment(double amount) {
System.out.println("Payment completed using debit card");
}
}
🔁 Interface Inheritance (UPI Example)
public interface UPIPayment extends Payment {
void validateUPINumber(String upiNumber);
}
public class PhonePePayment implements UPIPayment {
public void makePayment(double amount) {
System.out.println("Payment completed using PhonePe");
}
public void validateUPINumber(String upiNumber) {
// validation logic here
}
}
🧪 Real-Time Test Class (With Scanner)
public class InterfaceExampleTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
scanner.nextLine();
System.out.print("Please enter payment method: ");
String paymentMethod = scanner.nextLine();
Payment payment = null;
if (paymentMethod.equalsIgnoreCase("CREDIT")) {
payment = new CreditCardPayment();
} else if (paymentMethod.equalsIgnoreCase("DEBIT")) {
payment = new DebitCardPayment();
} else if (paymentMethod.equalsIgnoreCase("UPI")) {
payment = new PhonePePayment();
} else {
System.out.println("Invalid payment method");
}
if (payment != null) {
if (payment.isValidAmount(amount)) {
payment.makePayment(amount);
} else {
System.out.println("Invalid amount");
}
}
}
}
⚔️ Multiple Inheritance using Interface – Ambiguity
interface A1 {
default void print() {
System.out.println("print method in A1");
}
void display();
}
interface A2 {
void display();
default void print() {
System.out.println("display method A2");
}
}
class AClass implements A1, A2 {
@Override
public void display() {
System.out.println("display is called in AClass");
}
@Override
public void print() {
// You need to override if both interfaces have default methods with same signature
System.out.println("print method in AClass");
}
}
public class MultipleInheritanceUsingInterface {
public static void main(String[] args) {
A2 obj = new AClass();
obj.display();
AClass aClass = new AClass();
aClass.print();
}
}
📌 In real-time systems, imagine A1
and A2
are interfaces from different libraries (e.g., one for sending Email, one for sending SMS). If both define a send()
method as default, your implementation class must override it to avoid conflict.
🔁 Functional Interface in Java
A functional interface is an interface that has exactly one abstract method.
It is used mainly with lambda expressions and method references in Java.
Java provides some built-in functional interfaces in the java.util.function
package (like Consumer
, Supplier
, Predicate
, etc.)
✅ Example:
@FunctionalInterface
public interface NotificationSender {
void send(String message);
}
You can use it with a lambda:
public class FunctionalInterfaceExample {
public static void main(String[] args) {
NotificationSender emailSender = (message) -> {
System.out.println("Sending email: " + message);
};
emailSender.send("Hello from lambda!");
}
}
📌 Notes:
- A
@FunctionalInterface
annotation is optional but recommended. - Default and static methods do not count as abstract methods.
❓ Interview Tips & Questions
Q: Why use interfaces over abstract classes?
A: Interfaces provide full abstraction and allow multiple inheritance. Abstract classes are good when you need base implementation too.
Q: Can interfaces have variables?
A: Yes, but they are always public static final (constants).
Q: What’s new since Java 8 in interfaces?
A: Default and static methods with body.
Q: Can an interface extend another interface?
A: Yes.
Q: Can we create an object of an interface?
A: No, but we can reference it with implementing class.
✅ Summary
- Interfaces provide abstraction and flexibility.
- You can build polymorphic behavior easily.
- Use default methods to share logic.
- Functional interfaces help with cleaner lambda syntax.
- Interfaces support multiple inheritance without the diamond problem.
Leave a Reply