What is the difference between an interface and an abstract class in Java?

Both interfaces and abstract classes are used to achieve abstraction in Java, but they serve different purposes. An abstract class is used when related classes share common state and behavior, while an interface is used to define a contract that multiple unrelated classes can implement.

Key Points: • An abstract class can contain both abstract and concrete methods, whereas an interface primarily defines behavior contracts. • A class can extend only one abstract class but can implement multiple interfaces. • Abstract classes can have instance variables and constructors; interfaces cannot have constructors and generally contain constants. • Interfaces are ideal for achieving loose coupling and multiple inheritance. • Abstract classes are suitable when subclasses share common functionality.

Example: Consider a Vehicle abstraction. Common functionality can be placed in an abstract class, while additional capabilities such as charging or GPS tracking can be defined through interfaces.

Code Example:

abstract class Vehicle {

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

    abstract void fuelType();
}

interface Electric {

    void charge();
}

class ElectricCar extends Vehicle implements Electric {

    @Override
    void fuelType() {
        System.out.println("Runs on Electricity");
    }

    @Override
    public void charge() {
        System.out.println("Charging Vehicle");
    }
}

public class Demo {

    public static void main(String[] args) {

        ElectricCar car = new ElectricCar();

        car.start();
        car.fuelType();
        car.charge();
    }
}

Output:

Vehicle Started Runs on Electricity Charging Vehicle

Comparison:

Abstract Class: • Supports partial abstraction • Can have abstract and concrete methods • Can have constructors • Can have instance variables • Supports single inheritance

Interface: • Defines a contract for behavior • Can contain abstract, default, and static methods • Cannot have constructors • Can contain constants (public static final) • Supports multiple inheritance through implementation

When to Use:

Use Abstract Class: • When classes share common code and state • When you want to provide default implementations

Use Interface: • When defining capabilities or contracts • When multiple unrelated classes need the same behavior • When loose coupling is required

Interview Tip: A concise interview answer is:

"An abstract class is used to provide common state and behavior to related classes, while an interface defines a contract that classes must follow. A class can extend only one abstract class but can implement multiple interfaces. Interfaces are preferred for loose coupling and multiple inheritance, whereas abstract classes are useful for sharing common functionality."