Sobes.tech
Junior — Middle

How can you distinguish an abstract class from an interface in object-oriented programming?

sobes.tech AI

Answer from AI

An abstract class and an interface both define contracts in OOP, but they differ:

  • Abstract class can contain both abstract methods (without implementation) and concrete methods, as well as fields. A class can inherit from only one abstract class.

  • Interface contains only method declarations (in Java 8+ default methods with implementation are allowed), no state (fields). A class can implement multiple interfaces.

Example:

abstract class Animal {
    abstract void makeSound();
    void sleep() {
        System.out.println("Sleeping");
    }
}

interface Flyable {
    void fly();
}

class Bird extends Animal implements Flyable {
    void makeSound() {
        System.out.println("Chirp");
    }
    public void fly() {
        System.out.println("Flying");
    }
}