Abstract Classes
By the end of this lesson, you'll be able to:
- Explain what an abstract class is and why it can't be instantiated directly
- Write an abstract method that every subclass must implement
- Distinguish an abstract class from a regular virtual class
Prerequisites: "Virtual and Override"
A class you can never create directly
public abstract class Shape {
public abstract Decimal calculateArea();
}
// Shape s = new Shape(); // compile error — abstract classes cannot be instantiated
Shape on its own has no clear area formula — "calculate the area of a generic shape" doesn't mean anything until you know what kind of shape it is. abstract enforces that: you can never create a bare Shape, only specific subclasses of it.
abstract methods have no body — subclasses must supply one
public class Circle extends Shape {
public Decimal radius;
public override Decimal calculateArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
public Decimal width;
public Decimal height;
public override Decimal calculateArea() {
return width * height;
}
}
calculateArea() on Shape has no { } body at all — it's a contract, not an implementation. Any class that extends Shape is required to provide its own calculateArea(), or it fails to compile.
Abstract class vs regular virtual class
A virtual class can be instantiated on its own and may have methods a subclass chooses to override. An abstract class cannot be instantiated on its own, and any abstract methods it declares must be overridden by every subclass. Reach for abstract specifically when the parent's version genuinely shouldn't exist standalone.
Exercise
Write an abstract class PaymentMethod with an abstract method Decimal processFee(Decimal amount). Write a subclass CreditCard that implements processFee as amount * 0.03.
Show hint
public abstract Decimal processFee(Decimal amount); then override it in CreditCard.
Abstract Classes Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
An abstract class defines a shared shape that every subclass must follow but can never be created directly itself — useful when "generic version" genuinely makes no sense on its own.