close

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ObjectTest
{
    interface Printable
    {
        void print();
    }
    abstract class Shape
    {
        public abstract double area();
    }
    class Rectangle : Shape, Printable
    {
        public double width, height;
        public Rectangle(double w, double h)
        {
            width = w;
            height = h;
        }
        public override double area()
        {
            return width * height;
        }
        public void print()
        {
            Console.WriteLine("Rectangle:width=" + width + " height=" + height 
                                    + " area()=" + area());
        }
    }
    class Circle : Shape, Printable
    {
        public double r;
        public Circle(double r)
        {
            this.r = r;
        }
        public override double area()
        {
            return 3.14 * r * r;
        }
        public void print()
        {
            Console.WriteLine("Circle:r=" + r + " area()=" + area());
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle r1 = new Rectangle(5.0, 3.0);
            r1.print();
            Rectangle r2 = new Rectangle(4.0, 6.0);
            r2.print();
            Circle c1 = new Circle(1.0);
            c1.print();
            Circle c2 = new Circle(2.0);
            c2.print();
            Shape s = r1;
            double a = s.area();
            double areaSum = 0.0;
            Shape[] sa = new Shape[] { r1, r2, c1, c2 };
            for (int i = 0; i < sa.GetLength(0); i++)
            {
                double area = sa[i].area();
                areaSum = areaSum + area;
            }
            Console.WriteLine("areaSum=" + areaSum);
            Printable[] pa = new Printable[] { r1, r2, c1, c2 };
            foreach (Printable p in pa)
            {
                p.print();
            }
        }
    }
}

文章轉載:陳鍾誠 (2011年10月04日),(網頁標題) 形狀、矩形與圓形與可列印物件 — 介面 (interface) 與封裝、繼承、多型的概念整合。,(網站標題) 免費電子書:C# 程式設計,2011年10月04日,取自 http://cs0.wikidot.com/printableobject ,網頁修改第 1 版。

arrow
arrow
    創作者介紹
    創作者 Johnson峰 的頭像
    Johnson峰

    Johnson峰的部落格

    Johnson峰 發表在 痞客邦 留言(0) 人氣()