TOC

This article is currently in the process of being translated into Thai (~94% done).

Classes:

More abstract classes

ในบทที่แล้วเราได้เรียนเกี่ยวกับ abstract class บทนี้เราจะมาทำความเข้าใจกับ abstract ให้มากขึ้นด้วยการดูตัวอย่าง การนิยาม abstract ของ method ใน abstract class นั้น จะเหมือน method ทั่วไป เพียงแต่มันจะไม่มีโค้ดข้างใน

abstract class FourLeggedAnimal
{
    public abstract string Describe();
}

แล้วทำไมเราถึงไม่โค้ดใน abstract method? เพราะ abstract method จะไปถูกนิยามใน subclass ที่อาจจะแตกต่างกันไป มันจะทำให้ง่ายต่อการใช้และมีผลต่อการใช้งานในวันข้างหน้า เมื่อโปรแกรของเราซับซ้อนมากขึ้น

namespace AbstractClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Collections.ArrayList animalList = new System.Collections.ArrayList();
            animalList.Add(new Dog());
            animalList.Add(new Cat());
            foreach(FourLeggedAnimal animal in animalList)
                Console.WriteLine(animal.Describe());
            Console.ReadKey();
        }
    }

    abstract class FourLeggedAnimal
    {
        public abstract string Describe();
    }


    class Dog : FourLeggedAnimal
    {

        public override string Describe()
        {
            return "I'm a dog!";
        }
    }

    class Cat : FourLeggedAnimal
    {
        public override string Describe()
        {
            return "I'm a cat!";
        }
    }
}

เราได้สร้าง ArrayList ที่ประกอบไปด้วย instance object Dog และ Cat แต่ทุก object นั้นยังเป็น Animal object อยู่ เราไม่จำเป็นต้องรู้ว่าเป็น object จาก class ไหน compiler จะทำงานให้เราแทน แล้วจะเรียกใช้ Describe() method ได้ถูกต้อง


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!