What is Abstract Class in Java: Definition and Examples
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().
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(); } }
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.