Summary - Inheritance
Combine virtual/override and base to write a shape hierarchy.
Inheritance summary
In five lessons you learned C#'s inheritance mechanism. With a colon (:) a derived class reuses the base class's members. With base you reach base constructors and methods.
virtual and override give you polymorphism; sealed closes inheritance. Every class inherits from object and can override methods like ToString. Now you will combine all of this in two mini tasks.
Exercise Vehicle and Car inheritance hierarchy
Define a Vehicle base class with a public string Brand { get; set; } property. Then declare class Car : Vehicle with public int Doors { get; set; }. Inside Main create an instance with new Car { Brand = "Toyota", Doors = 4 } and print Brand.
Show example solution
Vehicle with Doors. In Main write Car c = new Car { Brand = "Toyota", Doors = 4 }; Console.WriteLine(c.Brand);
Example solution:
using System;
class Vehicle
{
public string Brand { get; set; }
}
class Car : Vehicle
{
public int Doors { get; set; }
}
class Program
{
static void Main()
{
Car c = new Car { Brand = "Toyota", Doors = 4 };
Console.WriteLine(c.Brand);
}
}
Exercise Add ToString override to Car
The Car class below already has Brand and Doors. Add a public override string ToString() method to Car with return Brand + " - " + Doors; in the body. Inside Main create an instance with new Car { Brand = "Toyota", Doors = 4 } and print it with Console.WriteLine(car).
Show example solution
public override string ToString() { return Brand + " - " + Doors; }. In Main write Car c = new Car { Brand = "Toyota", Doors = 4 }; Console.WriteLine(c);
Example solution:
using System;
class Vehicle
{
public string Brand { get; set; }
}
class Car : Vehicle
{
public int Doors { get; set; }
public override string ToString()
{
return Brand + " - " + Doors;
}
}
class Program
{
static void Main()
{
Car c = new Car { Brand = "Toyota", Doors = 4 };
Console.WriteLine(c);
}
}
Inheritance complete
Inheritance is now in your toolkit. With a colon you declare a derived class, with base you reach the base class, with virtual/override you get polymorphism, and with sealed you close the hierarchy.
The next group is a small helper library project where you will combine the class, constructor and inheritance knowledge you have built so far into a real mini application.
Test yourself
-
What does a virtual method do?
- Seals the class
- Allows overriding in a derived class
- Defines a static constructor
- Chains constructors
Show answer
Allows overriding in a derived class — Correct. virtual allows overriding in a derived class.
-
Complete the override declaration
public ____ string ToString() { return Title; }Show answer
public override string ToString() { return Title; }