What is an abstract class in Java?

Table of Contents

Introduction

An abstract class in Java is a class that cannot be instantiated on its own and is designed to be subclassed. It may contain abstract methods—methods without an implementation—along with concrete methods that have a defined behavior. This feature supports Java's object-oriented programming principles by allowing for a more structured and reusable codebase.

Characteristics of Abstract Classes

1. Cannot Be Instantiated

An abstract class cannot create objects directly. It serves as a blueprint for other classes.

Example:

In this example, attempting to create an instance of Animal results in a compilation error.

2. Can Contain Abstract and Concrete Methods

An abstract class can have both abstract methods (without a body) and concrete methods (with a body). This allows it to provide common functionality while still enforcing a contract for subclasses.

Example:

In this example, Vehicle defines an abstract method start() and a concrete method stop(). The Car class implements the start() method.

3. Can Have Constructors

Abstract classes can have constructors, which can be called when an object of a subclass is created. This is useful for initializing fields.

Example:

In this example, the constructor of the abstract class Shape is called in the subclass Circle.

Conclusion

Abstract classes in Java provide a powerful way to define templates for other classes. They allow developers to create a common interface while still maintaining the flexibility to define specific behaviors in subclasses. By leveraging abstract classes, programmers can promote code reuse and maintainability in their Java applications.

Similar Questions