0
0
JavaConceptBeginner · 3 min read

What is Abstract Class in Java: Definition and Examples

An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract methods without implementation. It serves as a blueprint for other classes to extend and provide specific method implementations.
⚙️

How It Works

Think of an abstract class as a blueprint for a house. You cannot live in the blueprint itself, but it shows how the house should be built. Similarly, an abstract class cannot create objects directly but defines methods and properties that other classes must follow.

In Java, an abstract class can have both fully defined methods and abstract methods (methods without a body). The abstract methods act like empty promises that the child classes must fulfill by providing their own code. This helps organize code and enforce a common structure among related classes.

💻

Example

This example shows an abstract class Animal with an abstract method sound(). The subclasses Dog and Cat provide their own versions of sound().

java
abstract class Animal {
    abstract void sound();

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

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

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

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.sound();
        dog.sleep();

        Animal cat = new Cat();
        cat.sound();
        cat.sleep();
    }
}
Output
Dog barks This animal is sleeping Cat meows This animal is sleeping
🎯

When to Use

Use an abstract class when you want to define a common template for a group of related classes but do not want to create objects of the base class itself. It is useful when some methods have a default behavior and others must be implemented by subclasses.

For example, in a game, you might have an abstract class Character with common properties like health and methods like move(). Specific characters like Wizard or Warrior will extend this class and define their own special attacks.

Key Points

  • An abstract class cannot be instantiated directly.
  • It can contain both abstract methods (without body) and concrete methods (with body).
  • Subclasses must implement all abstract methods or be abstract themselves.
  • It helps enforce a common interface and share code among related classes.

Key Takeaways

An abstract class defines a template with some methods to implement later.
You cannot create objects from an abstract class directly.
Subclasses must provide code for all abstract methods.
Use abstract classes to share code and enforce structure among related classes.