Member-only story
Top Interview Questions: Abstract Class vs. Interface in Java
Real-Life Scenarios
When to Use Abstract Classes
Scenario: Consider a software application for managing different types of vehicles. You may have a base class Vehicle
that provides common properties and methods for all vehicles, such as brand
, model
, and a method displayDetails()
. However, each specific vehicle type, such as Car
, Bike
, and Truck
, may have different behaviors, such as how they start or their specific fuel consumption.
Implementation:
abstract class Vehicle {
String brand;
String model;
Vehicle(String brand, String model) {
this.brand = brand;
this.model = model;
}
abstract void start(); // Abstract method
void displayDetails() {
System.out.println("Brand: " + brand + ", Model: " + model);
}
}
class Car extends Vehicle {
Car(String brand, String model) {
super(brand, model);
}
@Override
void start() {
System.out.println("Car is starting.");
}
}
When to Use Interfaces
Scenario: In a payment processing system, you may have different payment methods such as CreditCard
, PayPal
, and BankTransfer
. Each payment method will implement a common interface PaymentMethod
that requires the implementation of a method processPayment()
. This allows different payment methods to be used interchangeably.