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

An interface in Java is a blueprint of methods that a class must implement, while an abstract class is a class that cannot be instantiated but can contain both concrete and abstract methods. The main differences between them are:

  • In Java, a class can implement multiple interfaces but can only inherit from one abstract class.
  • Interfaces can only have abstract methods and constants, while abstract classes can have both concrete and abstract methods.
  • Interfaces are used to define contracts or behaviors that classes should adhere to, while abstract classes are used to provide common functionality for related classes.

Code Example

// Interface
interface Animal {
    void makeSound(); // Abstract method
    void eat(); // Abstract method
}

// Abstract class
abstract class Mammal {
    public void sleep() {
        System.out.println("Sleeping...");
    }
    abstract void move(); // Abstract method
}

// Concrete class implementing an interface and extending an abstract class
class Dog extends Mammal implements Animal {
    public void makeSound() {
        System.out.println("Bark!");
    }
    public void eat() {
        System.out.println("Eating...");
    }
    void move() {
        System.out.println("Running...");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.makeSound();
        dog.eat();
        dog.move();
        dog.sleep();
    }
}
Output
Bark!
Eating...
Running...
Sleeping...
Code Explanation

In this example, we have an interface called Animal and an abstract class called Mammal. The Animal interface declares two abstract methods: makeSound() and eat(). The Mammal abstract class contains a concrete method sleep() and an abstract method move().

The Dog class implements the Animal interface and extends the Mammal abstract class. It provides the implementations for the methods makeSound(), eat(), and move().

In the Main class, we create an instance of the Dog class and demonstrate the usage of methods. We can see that the Dog class implements the methods defined in the Animal interface and provides an implementation for the abstract method move() defined in the Mammal abstract class. Additionally, it inherits the sleep() method from the Mammal abstract class.

This example showcases how interfaces define contracts that classes must adhere to by implementing the required methods, while abstract classes can provide both concrete and abstract methods and can be extended by concrete classes.