Summary - Abstract classes
Combine abstract methods and override to write a shape hierarchy.
Summary - Abstract classes
In this group you learned abstract classes: an abstract class cannot be instantiated, an abstract method is bodyless and must be overridden, virtual is bodied and optional, a hierarchy provides a common template and sealed blocks inheritance or further overrides.
Abstract classes share common behavior and enforce a contract on subclasses. The next group dives into polymorphism: polymorphic behavior, method hiding and pattern matching.
Exercise Writer class (summary)
Add a public abstract void Write(string message); method to Writer. ConsoleWriter and Main are already in place; you only add the abstract method.
Show example solution
Add `public abstract void Write(string message);` to Writer. In Main write `Writer w = new ConsoleWriter(); w.Write("Hello");`.
Example solution:
using System;
abstract class Writer
{
public abstract void Write(string message);
}
class ConsoleWriter : Writer
{
public override void Write(string message)
{
Console.WriteLine(message);
}
}
class Program
{
static void Main()
{
Writer w = new ConsoleWriter();
w.Write("Hello");
}
}
Exercise Cat class (summary)
Define the Cat class: it inherits Animal and overrides Sound; the body returns "Meow". In Main, create Animal a = new Cat(); and call a.Greet();.
Show example solution
Animal { public override string Sound() { return "Meow"; } }`. In Main write `Animal a = new Cat(); a.Greet();`.
Example solution:
using System;
abstract class Animal
{
public abstract string Sound();
public void Greet()
{
Console.WriteLine("Sound: " + Sound());
}
}
class Cat : Animal
{
public override string Sound()
{
return "Meow";
}
}
class Program
{
static void Main()
{
Animal a = new Cat();
a.Greet();
}
}
Next step
Abstract classes provide common template and contract; an abstract method forces behavior on subclasses, virtual gives flexibility, sealed sets a boundary. The next group covers polymorphism: calling different subclass behaviors through an abstract class instance, method hiding with new and type checks with is/as.
Remember: an abstract class says "is-a"; an interface says "can-do". Together they enable powerful designs.
Test yourself
-
Which statement about abstract classes is correct?
- An abstract class can contain both bodied and bodyless methods.
- An abstract class can be instantiated with new.
- Abstract methods can have a body.
- A sealed abstract class can be defined.
Show answer
An abstract class can contain both bodied and bodyless methods. — Correct. An abstract class can contain both bodied and bodyless methods.
-
Fill in the blank: abstract method signature
abstract class Writer { public ____ void Write(string message); }Show answer
abstract class Writer { public abstract void Write(string message); }