2018年1月22日月曜日

開発環境

初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)日向 俊二 (翻訳)、オライリージャパン)の14章(ジェネリックとコレクション)、14.6(練習問題)、練習14-1.を取り組んでみる。

コード

using System;

namespace sample14_1
{
    abstract class Animal
    {
        private int weight;
        private string name;
        public Animal(int weight, string name)
        {
            this.weight = weight;
            this.name = name;
        }
        abstract public void Speak();
        abstract public void Move();

        public override string ToString()
        {
            return String.Format("Name: {0}, Weight: {1}", name, weight);
        }
    }
    class Cat: Animal
    {
        public Cat(int weight, string name) : base(weight, name) {}
        public override void Speak()
        {
            Console.WriteLine("にゃーにゃー");
        }
        public override void Move()
        {
            Console.WriteLine("スルスル");
        }
        public override string ToString()
        {
            return string.Format("[Cat] {0}", base.ToString());  
        }
    }
    class Dog: Animal
    {

        public Dog(int weight, string name) : base(weight, name) { }
        public override void Speak()
        {
            Console.WriteLine("わんわん");
        }
        public override void Move()
        {
            Console.WriteLine("テクテク");
        }
        public override string ToString()
        {
            return string.Format("[Dog] {0}", base.ToString());
        }    
    }
    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat(10, "cat1");
            Dog dog = new Dog(20, "dog1");
            Animal[] animals = { cat, dog };

            foreach (var item in animals)
            {
                Console.WriteLine(item);
            }
        }
    }
}

入出力結果(Terminal)

[Cat] Name: cat1, Weight: 10
[Dog] Name: dog1, Weight: 20

Press any key to continue...

0 コメント:

コメントを投稿