Abstract class hierarchy
Learn to build hierarchies with abstract classes.
Abstract class hierarchy
Abstract classes are useful for building multi-layer hierarchies. The top abstract class provides the common template; subclasses provide concrete behavior. Example: Vehicle abstract → Car, Motorcycle concrete.
This pattern uses a template method: a bodied method in the abstract class calls abstract methods that the subclass implements. Vehicle.Describe() is bodied and calls the abstract Start(); each subclass writes its own Start().
Template method pattern
In the template method pattern, the abstract class orchestrates the subclass's behavior. The bodied Describe() method says what to do in order; the Start() implemented by the subclass says how to do it.
This reduces code duplication and enforces consistency. All vehicles share the Describe() flow; each has a different Start() behavior. To add a new vehicle you only write a new subclass.
Exercise Vehicle hierarchy
Define the Car class: it inherits Vehicle and writes the public override void Start() body: Console.WriteLine("Car started with ignition");. In Main, create Vehicle v = new Car(); and call v.Describe();.
Show example solution
Vehicle { public override void Start() { Console.WriteLine("Car started with ignition"); } }`. In Main write `Vehicle v = new Car(); v.Describe();`.
Example solution:
using System;
abstract class Vehicle
{
public abstract void Start();
public void Describe()
{
Console.WriteLine("Vehicle running");
Start();
}
}
class Car : Vehicle
{
public override void Start()
{
Console.WriteLine("Car started with ignition");
}
}
class Program
{
static void Main()
{
Vehicle v = new Car();
v.Describe();
}
}
Test yourself
-
Fill in the blank: derived class
class Car ____ { public override void Start() { } }Show answer
class Car : Vehicle { public override void Start() { } } -
Match: hierarchy concepts
- base abstract
- common template
- concrete subclass
- implements methods
- template method
- bodied base method
- abstraction
- hides details
-
Which statement about abstract class hierarchies is correct?
- A derived class does not have to implement abstract methods.
- An abstract class provides a common template for derived classes.
- An abstract class can only contain one method.
- An abstract class can be instantiated with new.
Show answer
An abstract class provides a common template for derived classes. — Correct. An abstract class provides a common template for derived classes.