Skip to content
C

Abstract Class

An abstract class is a class that cannot be used to create objects directly. It can contain both fully implemented methods and abstract methods (methods with no body), which any subclass extending it must implement.


1. What is an Abstract Class?

An abstract class is a class that cannot be used to create objects directly. It can contain both fully implemented methods and abstract methods (methods with no body), which any subclass extending it must implement.

2. Why is it used?

It's useful when you want to define a common structure and some shared behaviour for related classes, while forcing each subclass to provide its own specific implementation for certain methods.

3. Real-Life Example

Think of a general job description like "Teacher," which describes common duties like "teach a subject," but the exact subject taught depends on the specific teacher. The abstract class defines the general role; each subclass fills in the specifics.

4. Syntax

java
abstract class ClassName { abstract void abstractMethod(); void normalMethod() { // regular implemented method } }

5. Example Program

java
abstract class Shape { abstract double area(); void describe() { System.out.println("This is a shape."); } } class Square extends Shape { double side = 5; double area() { return side * side; } } public class AbstractClassDemo { public static void main(String[] args) { Square sq = new Square(); sq.describe(); System.out.println("Area: " + sq.area()); } }

Output:

This is a shape.
Area: 25.0

6. Key Points to Remember

  • You cannot create an object of an abstract class directly using new.
  • An abstract class can still have constructors, fields, and fully implemented methods.
  • A subclass must implement all abstract methods, or it must also be declared abstract itself.