What is the difference between an abstract class and an interface in Java? Can you provide an example of when you would use each?

1 Answers
Answered by suresh

Abstract Class vs Interface in Java

Abstract Class vs Interface in Java

In Java, an abstract class and an interface are both used to define the structure of classes and provide common behavior, but they have key differences:

Abstract Class:

  • Can contain both abstract and non-abstract methods.
  • Can have fields, constructors, and method implementations.
  • Can extend only one class but implement multiple interfaces.

Interface:

  • Contains only abstract methods by default.
  • Cannot have method implementations or fields.
  • Supports multiple inheritance - a class can implement multiple interfaces.

Example Usage:

Abstract Class Example:

abstract class Animal {
    String name;
    
    public abstract void makeSound();
    
    public void printName() {
        System.out.println("Name: " + name);
    }
}

Interface Example:

interface Vehicle {
    void start();
    void stop();
}

class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car started");
    }
    
    @Override
    public void stop() {
        System.out.println("Car stopped");
    }
}

In summary, use an abstract class when you want to provide a common functionality along with abstract methods, and use an interface when you want to define a contract for classes to implement certain methods.

Answer for Question: What is the difference between an abstract class and an interface in Java? Can you provide an example of when you would use each?