← 講座に戻る: C# from scratch

Inheritance, override and abstract classes

動画は近日公開

In the real world many things share characteristics: a car, a motorcycle and a truck are vehicles; an employee and a customer are people. Inheritance lets you express that in code: a derived (or child) class takes everything a base (or parent) class has and adds its own things. With it you avoid copying and pasting properties and methods, and you keep what is common in a single place. It is declared with a colon: class Car : Vehicle.

A base class and its derived classes

The derived class inherits the public and protected members of the base; private ones remain hidden. A protected member is visible to the base class and its children, but not from outside. If the base has a constructor with parameters, the child must call it with : base(...). So that a derived class can change the behavior of a method, the base marks it as virtual and the child replaces it with override. Inside the child, the word base lets you call the original version, useful when you only want to add something. A class can inherit from only one base class, although it can implement several interfaces, as you will see in the next lesson.

csharp
var vehicles = new List<Vehicle>
{
    new Vehicle("Generic", 0),
    new Car("Civic", 4),
    new Motorcycle("Vespa"),
};

foreach (Vehicle v in vehicles)
{
    Console.WriteLine(v.Describe());
}
// Generic with 0 wheels
// Car Civic with 4 wheels and 4 doors
// Motorcycle Vespa with 2 wheels

class Vehicle
{
    public string Name { get; }
    protected int Wheels { get; }

    public Vehicle(string name, int wheels)
    {
        Name = name;
        Wheels = wheels;
    }

    public virtual string Describe() => $"{Name} with {Wheels} wheels";
}

class Car : Vehicle
{
    private readonly int _doors;

    public Car(string name, int doors) : base(name, 4)
    {
        _doors = doors;
    }

    public override string Describe() => $"Car {base.Describe()} and {_doors} doors";
}

class Motorcycle(string name) : Vehicle(name, 2)
{
    public override string Describe() => $"Motorcycle {Name} with {Wheels} wheels";
}

Polymorphism in action

Notice the loop in the example: the list is of Vehicle, but each element answers with its own Describe. This is called polymorphism, "many forms": whoever calls v.Describe() does not need to know which concrete type they have in front of them. C# decides at run time which version to use. An object of the child class can always be stored in a variable of the base type, because a Car is a Vehicle. The opposite is not automatic: to treat a Vehicle as a Car you have to check the type with is or as, or with pattern matching, and then access what is specific to Car.

Abstract and sealed classes

Sometimes the base class is just a general idea that makes no sense to create directly: what is a plain "Animal"? For that there is abstract: an abstract class cannot be instantiated with new, and it can declare abstract methods without a body that each child is required to implement. On the other hand, sealed prevents a class from having children or an overridden method from being overridden again. A design tip: prefer composition (an object that contains another) over long inheritance chains; inheriting three or four levels usually makes the code rigid and hard to understand.

csharp
Shape[] shapes = [new Circle(1), new Rectangle(2, 3)];
foreach (Shape s in shapes)
{
    Console.WriteLine($"{s.Name}: area {s.Area():0.00}");
}
// Circle: area 3.14
// Rectangle: area 6.00

// var s = new Shape();           // ERROR: cannot instantiate an abstract class

if (shapes[1] is Rectangle rect)   // type check + variable
{
    Console.WriteLine(rect.Width); // 2
}

abstract class Shape
{
    public abstract string Name { get; }
    public abstract double Area();
}

class Circle(double radius) : Shape
{
    public override string Name => "Circle";
    public override double Area() => Math.PI * radius * radius;
}

class Rectangle(double width, double height) : Shape
{
    public double Width => width;
    public override string Name => "Rectangle";
    public override double Area() => width * height;
}

理解度チェック

問題 1 / 2

Which word lets a child class replace a base method?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →