Abstract classes let you create a base blueprint for other classes. They help share common code but cannot be used to make objects directly.
Abstract classes in Java
abstract class Animal { // Abstract method (no body) abstract void makeSound(); // Regular method void sleep() { System.out.println("Sleeping..."); } }
An abstract class is declared with the keyword abstract.
It can have both abstract methods (without body) and regular methods (with body).
Vehicle is abstract and Car provides the method body.abstract class Vehicle { abstract void startEngine(); } class Car extends Vehicle { void startEngine() { System.out.println("Car engine started"); } }
area() must be implemented by Circle.abstract class Shape { abstract double area(); } class Circle extends Shape { double radius; Circle(double radius) { this.radius = radius; } double area() { return Math.PI * radius * radius; } }
plugIn() and abstract methods like turnOn().abstract class Appliance { void plugIn() { System.out.println("Plugged in"); } abstract void turnOn(); } class Fan extends Appliance { void turnOn() { System.out.println("Fan is on"); } }
This program shows an abstract class Animal with an abstract method makeSound() and a regular method sleep(). The subclasses Dog and Cat implement makeSound(). We cannot create an Animal object directly.
abstract class Animal { abstract void makeSound(); void sleep() { System.out.println("Sleeping..."); } } class Dog extends Animal { void makeSound() { System.out.println("Bark"); } } class Cat extends Animal { void makeSound() { System.out.println("Meow"); } } public class Main { public static void main(String[] args) { // Animal animal = new Animal(); // Error: Cannot instantiate abstract class Dog dog = new Dog(); Cat cat = new Cat(); System.out.println("Dog says:"); dog.makeSound(); dog.sleep(); System.out.println("Cat says:"); cat.makeSound(); cat.sleep(); } }
Time complexity depends on the methods implemented in subclasses, not the abstract class itself.
Abstract classes use memory only when instantiated through subclasses.
Common mistake: Trying to create an object of an abstract class directly causes a compile error.
Use abstract classes when you want to share code and force subclasses to implement certain methods. Use interfaces if you only want to define method signatures without any code.
Abstract classes cannot be instantiated but can have both abstract and regular methods.
Subclasses must implement all abstract methods.
They help organize code by sharing common behavior and enforcing method implementation.