Sobes.tech
Junior — Middle

Can you give an example of an abstract class in object-oriented programming?

sobes.tech AI

Answer from AI

An abstract class is a class that is not intended to be instantiated directly, but serves as a base class for other classes. It can contain both implemented methods and abstract methods (without implementation), which must be implemented in subclasses.

Example of an abstract class in Java (Android):

public abstract class Animal {
    // Abstract method — must be implemented in subclasses
    public abstract void makeSound();

    // Regular method with implementation
    public void sleep() {
        System.out.println("Animal is sleeping");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

// Usage
Animal dog = new Dog();
dog.makeSound(); // Outputs: Woof!
dog.sleep();     // Outputs: Animal is sleeping

In this example, Animal is an abstract class with an abstract method makeSound(). The class Dog inherits from Animal and implements this method.