abstract class
Learn to define and derive an abstract class.
Abstract class
An abstract class cannot be instantiated directly and is designed to be inherited. Declaration: abstract class Animal { ... }.
An abstract class can hold both bodied methods and abstract methods (bodyless signatures). Calling new Animal() is a compile error; but you can use it through an instance of a derived class: Animal a = new Dog();. This is useful to share common behavior.
Cannot instantiate but can be inherited
An abstract class cannot be created with new: new Animal() is a compile error. Instead you define a subclass and instantiate it: class Dog : Animal { ... }.
The subclass must implement all the abstract class's abstract methods. Otherwise you get a compile error. This way the abstract class acts as a template for subclasses. Common fields and helper methods live in the abstract class; details are left to subclasses.
Exercise Animal class
Define the Animal abstract class with a public string Name; field and a public abstract void MakeSound(); method. Dog and Main are already in place; you only add the abstract class.
Show example solution
Define Animal as `abstract class Animal { public string Name; public abstract void MakeSound(); }`. In Main write `Animal a = new Dog(); a.Name = "Rex"; Console.WriteLine(a.Name); a.MakeSound();`.
Example solution:
using System;
abstract class Animal
{
public string Name;
public abstract void MakeSound();
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof woof");
}
}
class Program
{
static void Main()
{
Animal a = new Dog();
a.Name = "Rex";
Console.WriteLine(a.Name);
a.MakeSound();
}
}
Test yourself
-
Fill in the blank: abstract class
abstract ____ { public string Name; public abstract void MakeSound(); }Show answer
abstract class Animal { public string Name; public abstract void MakeSound(); } -
Which statement about abstract classes is correct?
- An abstract class can be instantiated with new.
- An abstract class can only contain methods.
- An abstract class is designed to be inherited.
- An abstract class can be sealed.
Show answer
An abstract class is designed to be inherited. — Correct. An abstract class is designed to be inherited; it cannot be instantiated directly.
-
Match: abstract class concepts
- abstract class
- designed for inheritance
- new Animal()
- compile error
- abstract method
- bodyless signature
- override
- body in derived class