Abstract Classes
in Java
Learn how to define shared behavior using abstract classes, enforce method contracts with abstract methods, and build flexible class hierarchies.
What Is an Abstract Class?
An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes. You declare it with the abstract keyword.
Why Use Abstract Classes?
Anatomy of an Abstract Class
The Rules of Abstract Classes
Abstract vs Concrete Methods
| Abstract Method | Concrete Method | |
|---|---|---|
| Has a body? | No: ends with a semicolon | Yes: has { } with code |
| Keyword | abstract required | No special keyword |
| Subclass duty | Must override | Can override or inherit |
| Purpose | Define a contract | Provide shared logic |
Abstract Class vs Interface
| Abstract Class | Interface | |
|---|---|---|
| Inheritance | Single (extends one) | Multiple (implements many) |
| Constructors | Yes | No |
| Instance fields | Yes | Only static final |
| Concrete methods | Yes | Only default (Java 8+) |
| Best for | IS-A with shared state | CAN-DO capability |
How to Design with Abstract Classes
Example 1: Shape Hierarchy
Extending Shape: Subclasses
Example 2: Animal Hierarchy
Subclasses of Animal
Example 3: Constructors and Fields
Polymorphism in Action
Common Mistakes
Summary: Abstract Class Checklist
| Feature | Abstract Class Can... |
|---|---|
| Be instantiated directly | No |
| Have constructors | Yes |
| Have instance variables | Yes |
| Have abstract methods | Yes (no body) |
| Have concrete methods | Yes (with body) |
| Be extended by one class | Yes (single inheritance) |
| Use polymorphism | Yes (declare as abstract type) |
Question 1 of 5
Which of the following statements about abstract classes in Java is true?
Question 2 of 5
Given the following code:
public abstract class Pet { public abstract String sound(); } public class Parrot extends Pet { // body omitted }
What happens if Parrot does not override the sound() method?
Question 3 of 5
Consider: Shape s = new Circle("blue", 3);
What does s.area() return?
Question 4 of 5
What is the primary advantage of an abstract class over an interface in Java?
Question 5 of 5
Given:
public abstract class Appliance { private boolean on; public Appliance() { on = false; } public void turnOn() { on = true; } public abstract void operate(); } public class Blender extends Appliance { @Override public void operate() { System.out.println("Blending!"); } }
What is the result of this code?
Appliance a = new Blender(); a.turnOn(); a.operate();