多型Polymorphism在物件導向程式語言的意思是一件事物有多種不同樣貌,就好像面積的計算會因為不同形狀有不同算法,三角形是底乘以高除以2,長方形是長乘以寬。有關於多型的觀念可以看看下面這篇文章:

多型Polymorphism

 

下面我將使用物件導向的抽象Abstract和介面Interface搭配多型Polymorphism來實作面積計算,使用的程式為C#。抽象的意思是對於要描述的東西找到共通必要的元素,介面則是像日常生活中不同的電腦產品,有相同的規格,像是USB。有關於抽象和介面的觀念介紹可以看一下這2篇文章:

抽象Abstract

介面Interface

 

 

使用抽象Abstract實作面積計算

public abstract class Shape

    {

        public abstract int Area(int x,int y);

    }

    public class Square:Shape

    {

        public override int Area(int x, int y)

        {

            return x * y;

        }

    }

    public class Triangle : Shape

    {

        public override int Area(int x, int y)

        {

            return x * y / 2;

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Square square = new Square();

            Triangle triangle = new Triangle();

            Console.WriteLine("邊長(5,10)的長方形的面積為:" + square.Area(5, 10));

            Console.WriteLine("底為5,高為10的三角形的面積為:" + triangle.Area(5, 10));

        }      

    }

 

程式執行結果

邊長(5,10)的長方形的面積為:50

底為5,高為10的三角形的面積為:25

 

 

使用介面interface實作面積計算

public interface Shape

    {

        public int Area(int x, int y);

    }

 

    public class Triangle : Shape

    {

        public int Area(int x, int y)

        {

            return x * y / 2;

        }

    }

 

    public class Square : Shape

    {

        public int Area(int x, int y)

        {

            return x * y;

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Square square = new Square();

            Triangle triangle = new Triangle();

 

            Console.WriteLine("邊長(5,10)的長方形的面積為:" + square.Area(5, 10));

            Console.WriteLine("底為5,高為10的三角形的面積為:" + triangle.Area(5, 10));

        }

    }

 

程式執行結果

邊長(5,10)的長方形的面積為:50

底為5,高為10的三角形的面積為:25

 

使用抽象Abstract和介面Interface一樣做面積計算,寫法只有幾個地方不一樣,首先當然就是一個是前面加上Abstract,一個是前面加上Interface,另外就是在使用Abstract時繼承的子類別所引用到父類別的方法前面要加上override,使用Interface時則不需要。抽象和介面還有很多的不同,想要了解的朋友可以看一下下面的這一篇文章:

抽象和介面的差異

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 波羅、希夏普2020 的頭像
    波羅、希夏普2020

    希夏普2020的程式天地

    波羅、希夏普2020 發表在 痞客邦 留言(0) 人氣()