c# · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
lets one class build on another.
Dogs and cats are both animals: each has a name, and they all eat. Inheritance lets one class build on another, so you write the shared parts once. class Dog : Animal reads as “a Dog is an Animal”.
Animal is the and Dog is the Name and Eat, and adds extras of its own, like Fetch.
Animal's constructor needs a name, so Dog's constructor passes one along: : base(name) runs the base constructor first. The word base always means the class you built on. Leave it out and C# refuses with CS7036.
using System;
var dog = new Dog("Rex");
dog.Eat();
dog.Fetch();
class Animal
{
public string Name { get; set; }
public Animal(string name) { Name = name; }
public void Eat() { Console.WriteLine($"{Name} is eating."); }
}
class Dog : Animal
{
public Dog(string name) : base(name) { }
public void Fetch() { Console.WriteLine($"{Name} fetches the ball."); }
} { } is an empty body: the base constructor does all the work.
guess first
Does a car have wheels? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
var car = new Car();
car.Wheels = 4;
car.Honk();
Console.WriteLine($"{car.Wheels} wheels");
class Vehicle
{
public int Wheels { get; set; }
}
class Car : Vehicle
{
public void Honk() { Console.WriteLine("Beep!"); }
}
your turn
Your turn. Make a cat that is an animal.
On line 14, make Cat build on Animal. On line 16, pass the name to the base constructor. On line 17, choose what the cat says, then press run.
output
press run to see what happens
fix it
The teacher will not build. Can you fix it?
output
press run to see what happens
- C# says
CS7036on line 15: thePersonconstructor needs aname, and nobody gives it one. - A derived constructor must pass the name on to the base constructor before its own body runs.
- Change line 15 to
public Teacher(string name, string subject) : base(name), then press run.
nailed it
your classes have a family tree. :D
class Dog : Animalbuilds Dog on Animal.- A derived class inherits members and can add more.
: base(...)runs the base constructor first.
new words in your collection
- inheritance
- base class
- derived class
- base
This lesson isn’t saved. A free account remembers every lesson you finish.