形狀、矩形與圓形 — 封裝、繼承、多型的概念整合。

基礎篇

C# 簡介

開發環境

變數與運算

流程控制

陣列

函數

物件

例外處理

函式庫篇

檔案處理

資料結構

正規表達式

Thread

應用篇

視窗程式

媒體影音

網路程式

遊戲程式

手機程式

資料庫

雲端運算

特殊功能

委派

擴展方法

序列化

LinQ

WPF

網路資源

教學影片

投影片

教學文章

軟體下載

考題解答

101習題

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectTest
{
    abstract class Shape
    {
        public abstract double area();
    }

    class Rectangle : Shape
    {
        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("width=" + width + " height=" + height + " area()=" + area());
        }
    }

    class Circle : Shape
    {
        public double r;

        public Circle(double r)
        {
            this.r = r;
        }

        public override double area()
        {
            return 3.14 * r * r;
        }

        public void print()
        {
            Console.WriteLine("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);
        }
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License