Abstract and concrete classes help organize code by defining what things can do and how they do it. Abstract classes set rules, while concrete classes fill in the details.
Abstract vs concrete classes in Java
abstract class Animal { // Abstract method (no body) abstract void makeSound(); // Concrete method (has body) void sleep() { System.out.println("This animal is sleeping."); } } class Dog extends Animal { // Must implement abstract method void makeSound() { System.out.println("Woof Woof"); } } class Cat extends Animal { void makeSound() { System.out.println("Meow"); } }
An abstract class cannot be used to create objects directly.
Concrete classes must implement all abstract methods from their abstract parent.
abstract class Vehicle { abstract void startEngine(); } class Car extends Vehicle { void startEngine() { System.out.println("Car engine started."); } }
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; } }
abstract class EmptyAbstract { abstract void doNothing(); } // No concrete class yet, so no objects can be created.
class ConcreteClass { void greet() { System.out.println("Hello!"); } } // Concrete class can be used to create objects directly.
This program shows an abstract class Animal with an abstract method makeSound() and a concrete method sleep(). Dog and Cat are concrete classes that implement makeSound(). We create Dog and Cat objects and call their methods.
abstract class Animal { abstract void makeSound(); void sleep() { System.out.println("This animal is sleeping."); } } class Dog extends Animal { void makeSound() { System.out.println("Woof Woof"); } } 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: Abstract vs concrete classes do not affect time complexity directly; they organize code structure.
Space complexity: No extra space cost; just class definitions.
Common mistake: Trying to create an object from an abstract class causes a compile error.
Use abstract classes when you want to define a common interface and share code but prevent direct instantiation.
Use concrete classes when you want to create usable objects with full behavior.
Abstract classes define methods without full details and cannot create objects directly.
Concrete classes provide full method details and can create objects.
Use abstract classes to set rules and concrete classes to do the actual work.