← Back to Chapters

Java Abstract Class

? Java Abstract Class

? Quick Overview

An abstract class in Java is a class that cannot be instantiated and is designed to be inherited. It may contain abstract methods (without implementation) as well as concrete methods (with implementation).

? Key Concepts

  • Declared using the abstract keyword
  • Cannot create objects directly
  • Can contain abstract and non-abstract methods
  • Supports constructors and instance variables
  • Used to achieve partial abstraction

? Syntax / Theory

An abstract method does not have a body and must be implemented by child classes. If a class contains at least one abstract method, the class itself must be declared abstract.

? View Code Example
// Abstract class defining a common structure
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Animal is sleeping");
}
}

? Code Example(s)

? View Code Example
// Concrete class implementing abstract methods
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
? View Code Example
// Main class to test abstract class behavior
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
a.sleep();
}
}

? Live Output / Explanation

Output

Dog barks
Animal is sleeping

The abstract reference Animal points to a Dog object. The implemented sound() method of Dog is executed at runtime.

? Interactive Demo: Abstraction in Action

See how the Shape abstract class works with different implementations. Change the inputs below and run the Java code.

 
// Click Run to see output...

✅ Tips & Best Practices

  • Use abstract classes when classes share common behavior
  • Prefer abstract classes over interfaces when method implementation is required
  • Do not overuse abstraction; keep designs simple
  • Use abstract methods to enforce implementation rules

? Try It Yourself

  • Create an abstract class Shape with method area()
  • Implement it using Circle and Rectangle classes
  • Test polymorphism using abstract references