Difference between abstract class and interface in Java

In Java, both abstract classes and interfaces provide a way to define a contract that a class can follow, but they differ in their implementation and purpose.


Here are the key differences between abstract classes and interfaces in Java:


  1. 1. Implementation: An abstract class can have both concrete and abstract methods, while an interface can only have abstract methods. Abstract classes can also have instance variables and constructors, but interfaces cannot.


  2. 2. Inheritance: A class can only inherit from one abstract class, but it can implement multiple interfaces.


  3. 3. Accessibility: Abstract classes can have different access modifiers for their methods and variables, while interfaces are always public.


  4. 4. Purpose: Abstract classes are typically used to provide a base implementation for derived classes, while interfaces define a contract for a class to implement.


In summary, abstract classes provide a way to define a base class with some default implementation, while interfaces provide a way to define a set of methods that a class must implement. The choice between using an abstract class or an interface depends on the specific requirements of the project and the design choices of the developer.


Here are some examples to help illustrate the differences between abstract classes and interfaces in Java:


Example of an Abstract Class:

public abstract class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public abstract void makeSound();

    public void eat(String food) {
        System.out.println(name + " is eating " + food);
    }
}


In this example, Animal is an abstract class that defines a constructor, an abstract method makeSound(), and a concrete method eat(). Any derived class that extends the Animal class must implement the makeSound() method, but can use the eat() method as-is.


Example of an Interface:

public interface Vehicle {
    void start();
    void stop();
    int getSpeed();
}


In this example, Vehicle is an interface that defines three abstract methods: start(), stop(), and getSpeed(). Any class that implements the Vehicle interface must provide an implementation for these three methods.


To give a concrete example of a class that implements this interface:

public class Car implements Vehicle {
    private int speed;

    public void start() {
        // implementation for starting the car
    }

    public void stop() {
        // implementation for stopping the car
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }
}


In this example, Car implements the Vehicle interface, providing implementations for the three methods defined in the interface.