Can you provide examples of when to use an interface versus when to extend a class?

The choice between an interface and class inheritance depends on the relationship between the classes and the level of code reuse required. Interfaces are used to define a contract or capability, while inheritance is used when classes share a common parent-child relationship and behavior.

Key Points: • Use an interface when different classes need to provide the same behavior but are not closely related. • Use class inheritance when there is a clear "is-a" relationship between the classes. • Interfaces promote loose coupling and flexibility. • Inheritance promotes code reuse by sharing common fields and methods. • A class can implement multiple interfaces but can extend only one class.

When to Use an Interface:

Use an interface when you want to define a common capability that can be implemented by unrelated classes.

Examples: • Payment Processing (Credit Card, UPI, PayPal) • Logging (File Logger, Database Logger) • Notifications (Email, SMS, Push Notification)

Code Example:

interface Payment {

    void pay(double amount);
}

class CreditCardPayment implements Payment {

    @Override
    public void pay(double amount) {
        System.out.println("Paid using Credit Card");
    }
}

class UpiPayment implements Payment {

    @Override
    public void pay(double amount) {
        System.out.println("Paid using UPI");
    }
}

Here, the classes are not part of the same hierarchy but share a common capability.

When to Extend a Class:

Use inheritance when the child class is a specialized version of the parent class and can reuse its state and behavior.

Examples: • Dog extends Animal • Car extends Vehicle • Manager extends Employee

Code Example:

class Vehicle {

    void start() {
        System.out.println("Vehicle Started");
    }
}

class Car extends Vehicle {

    void drive() {
        System.out.println("Car is Driving");
    }
}

Here, Car is a type of Vehicle, making inheritance a natural choice.

Real-World Comparison:

Interface: • Defines capabilities • Represents a "can-do" relationship • Example: Bird can Fly

Inheritance: • Defines hierarchy • Represents an "is-a" relationship • Example: Dog is an Animal

Interview Tip: A concise interview answer is:

"Use an interface when you want to define a contract that multiple unrelated classes can implement. Use class inheritance when there is a true 'is-a' relationship and the child class needs to reuse or extend the behavior of the parent class. In modern Java applications, interfaces are generally preferred because they provide loose coupling and greater flexibility."