Abstract Class vs Interface in Java
Abstract Class
An abstract class is a partially implemented class. It can contain both abstract methods (no body) and concrete methods (with body). It is useful when you want to provide a common base with shared code across related classes.
// Example: Abstract Class
abstract class Payment {
abstract void pay(double amount);
void printReceipt() {
System.out.println("Receipt generated.");
}
}
class CreditCardPayment extends Payment {
void pay(double amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
Interview Tip: Abstract classes are best when you want to enforce a template but also provide default behavior.
Interface
An interface defines a contract. It contains abstract methods (and default/static methods since Java 8). Interfaces are ideal when you want to enforce capabilities across unrelated classes.
// Example: Interface
interface Payable {
void pay(double amount);
}
class UpiPayment implements Payable {
public void pay(double amount) {
System.out.println("Paid " + amount + " using UPI.");
}
}
class WalletPayment implements Payable {
public void pay(double amount) {
System.out.println("Paid " + amount + " using Wallet.");
}
}
Interview Tip: Interfaces are best when you want multiple classes (even unrelated ones) to share a common behavior.
Comparison Table
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have abstract + concrete methods | Traditionally only abstract (default/static since Java 8) |
| Variables | Can have instance variables | Only constants (public static final) |
| Inheritance | Single inheritance (extends one class) | Multiple inheritance (implements many interfaces) |
| Use Case | When classes share a common base and partial implementation | When classes need to share a contract across hierarchies |
| Flexibility | Less flexible (tight coupling) | More flexible (loose coupling) |
When to Use Each (Interview-Ready Notes)
- Abstract Class: Use when you have a base class with default behavior. Example: Payment system where all payments generate a receipt, but the payment method varies.
- Interface: Use when you want to enforce a capability across unrelated classes. Example: Serializable or Comparable β any class can implement them regardless of hierarchy.
- Rule of Thumb: If you need is-a relationship β Abstract Class. If you need can-do relationship β Interface.
- Interview Scenario: If asked βWhich one would you choose for designing a payment gateway?β β Say: βIβd use an abstract class for shared payment logic (like receipt generation) and interfaces for capabilities like
RefundableorPayablethat can apply across different payment types.β