開発環境
- Microsoft Windows 7 Home Premium (OS)
- Microsoft Visual C# 2010 Express Edition (IDE)
- 言語: C#
独習C# 第3版 ハーバート・シルト (著) エディフィストラーニング株式会社 矢嶋聡 (監修, 翻訳) の第8章(C継承)の理解度チェック13、14を解いてみる。
13, 14.
コード
using System; public abstract class Shape { public Shape(int w, int h) { Width = w; Height = h; } public int Width { get; protected set; } public int Height { get; protected set; } public abstract int CalcArea(); } public class Triangle : Shape { public Triangle(int w, int h) : base(w, h) { } public override int CalcArea() { return Width * Height / 2; } } public class Rectangle : Shape { public Rectangle(int w, int h) : base(w, h) { } public override int CalcArea() { return Width * Height; } } class Tester { public void Run() { Triangle t = new Triangle(100, 50); Rectangle r1 = new Rectangle(10, 10); Rectangle r2 = new Rectangle(10, 30); Shape[] shapes = { t, r1, r2 }; foreach (Shape shape in shapes) { Console.WriteLine( "{0} 幅:{1}, 高さ:{2}, 面積:{3}", shape.GetType(), shape.Width, shape.Height, shape.CalcArea()); } } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
Triangle 幅:100, 高さ:50, 面積:2500 Rectangle 幅:10, 高さ:10, 面積:100 Rectangle 幅:10, 高さ:30, 面積:300 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿