Abstract in Java – Definition, Syntax, and Example


2. Abstract Class in Java

In Java, an abstract class is a class that cannot be instantiated (you cannot create objects of it) and is meant to be extended by other classes.

It provides a common base for multiple classes, allowing some methods to remain undefined (abstract methods) so subclasses can provide their own implementations.

An abstract class:

  • Can have abstract methods (methods without a body).
  • Can have non-abstract methods (methods with a body).
  • Can have constructors, fields, and static methods.
  • Can implement interfaces.
  • Must be declared using the keyword abstract.

Key Points

  • If a class has at least one abstract method, it must be declared abstract.
  • Abstract methods do not have a body and end with a semicolon.
  • A subclass extending an abstract class must override all abstract methods or be declared abstract itself.
  • Abstract classes can have constructors called when a subclass object is created.

Syntax

abstract class ClassName {
    // abstract method (no body)
    abstract void display();

    // regular method
    void show() {
        System.out.println("This is a concrete method in abstract class");
    }
}

Example

// Abstract class
abstract class Animal {
    // Abstract method (no body)
    abstract void sound();

    // Concrete method
    void sleep() {
        System.out.println("Sleeping...");
    }
}

// Subclass (must override abstract method)
class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        // Animal a = new Animal(); // Not allowed (abstract class)

        Dog d = new Dog();
        d.sound(); // Bark
        d.sleep(); // Sleeping...
    }
}

Output

Bark
Sleeping...


Frequently Asked Questions (FAQ)

What is an abstract class in Java?
An abstract class is a class that cannot be instantiated and is designed to be extended by subclasses. It can contain abstract and non-abstract methods.
Can we create an object of an abstract class?
No, you cannot create objects of an abstract class directly.
Can an abstract class have constructors?
Yes, abstract classes can have constructors which are called when a subclass object is created.
What happens if a subclass does not override all abstract methods?
The subclass must be declared abstract if it does not override all abstract methods.
Can abstract class implement interfaces?
Yes, abstract classes can implement interfaces.

Comments

Popular posts from this blog

Introduction to Java

Java Classes in Depth – Complete Guide with Definitions, Syntax & Examples

Top AI Tools for Social Media Marketing in 2025 – Automate & Grow Your Brand