2018年4月30日月曜日

開発環境

初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)日向 俊二 (翻訳)、オライリージャパン)の11章(継承とポリモーフィズム)、11.9(練習問題)、練習11-3.を取り組んでみる。

コード

using System;

class Program
{
    public void Run()
    {
        DigitalPhone dp = new DigitalPhone();
        TalkingPhone ep = new TalkingPhone();

        Telephone[] telephones = { dp, ep };

        foreach (Telephone tp in telephones)
        {
            tp.Ring();
        }
    }
    static void Main(string[] args)
    {
        Program p = new Program();
        p.Run();
    }
}

abstract class Telephone
{
    protected string phonetype = "Telephone";

    public abstract void Ring();
}

class DigitalPhone: Telephone
{
    public DigitalPhone()
    {
        this.phonetype = "Digital";
    }

    public override void Ring()
    {
        Console.WriteLine("Ringing the " + this.phonetype);
    }
}

class TalkingPhone : Telephone
{
    public TalkingPhone()
    {
        this.phonetype = "Talking";
    }

    public override void Ring()
    {
        Console.WriteLine("Ringing the " + this.phonetype);
    }
}

入出力結果(コマンドプロンプト)

Ringing the Digital
Ringing the Talking
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿