0
0
Javaprogramming~5 mins

Abstract methods in Java

Choose your learning style9 modes available
Introduction

Abstract methods let you define a method without giving its details. This means subclasses must provide their own version of the method.

When you want to create a general class that other classes will build on.
When you want to force subclasses to implement specific behavior.
When you have a method that makes sense only in subclasses, not in the base class.
Syntax
Java
abstract class ClassName {
    abstract returnType methodName(parameters);
}

The class containing an abstract method must be declared abstract.

Abstract methods have no body (no curly braces, just a semicolon).

Examples
This abstract class Animal has an abstract method makeSound. Subclasses must define how to make a sound.
Java
abstract class Animal {
    abstract void makeSound();
}
Shape class has an abstract method area. Each shape subclass will calculate area differently.
Java
abstract class Shape {
    abstract double area();
}
Vehicle has an abstract method startEngine. Car provides its own version.
Java
abstract class Vehicle {
    abstract void startEngine();
}

class Car extends Vehicle {
    @Override
    void startEngine() {
        System.out.println("Car engine started");
    }
}
Sample Program

This program shows an abstract class Animal with an abstract method makeSound. Dog and Cat classes provide their own sounds. The sleep method is shared.

Java
abstract class Animal {
    abstract void makeSound();

    void sleep() {
        System.out.println("Animal is sleeping");
    }
}

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

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();

        dog.makeSound();
        dog.sleep();

        cat.makeSound();
        cat.sleep();
    }
}
OutputSuccess
Important Notes

Time complexity: Abstract methods themselves do not affect time complexity; it depends on the subclass implementation.

Space complexity: No extra space is used by abstract methods alone.

Common mistake: Forgetting to implement all abstract methods in subclasses causes compile errors.

Use abstract methods when you want to force subclasses to provide specific behavior, unlike normal methods that can have default behavior.

Summary

Abstract methods have no body and must be implemented by subclasses.

Classes with abstract methods must be declared abstract.

Abstract methods help design flexible and reusable code by defining a contract for subclasses.