มันเป็นเรื่องยากมากที่จะบอกความแตกต่าง หากไม่เคยลองมา implement เอง

[O]bject [O]riented [P]rogramming

The basic concept of OOP : Class » Object » Instance.

Class

is Blueprint / Template ซึ่งจะระบุถึง #stages (field), #behavior (method) และ #constructor อะไรบ้าง? ซึ่งบางภาษาอาจจะมี class variable หรือ static method ซึ่งจะเป็นตัวแปลที่อยู่กับคลาส อาจจะใช้นับจำนวน instance หรือระบุเอกลักษ์บางอย่างของ class ซึ่งทุกๆ instance เหมือนกันหมด

Object

is a Copy of the class ซึ่งจะถูกสร้างขึ้นใน memory เมื่อทำการ new ขึ้นมา เสมือนการนำ blueprint ไปสร้างมาเป็น วัตถุจริงๆ

Instance

is a Reference variable ซึ่งจะอ้างอิงไปถึง address ของ Object ใน memory

A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance. -- Joe Snyder[1]

Example

From Class A has Object1 , Object2 and Object3

Object1จะมีค่าทุกอย่างเหมือน Object2 และ Object3 แต่อยู่คนละที่ใน Memory

From Object1 has obj1_Instance1 obj1_Instace2 and obj1_Instance3

ทุกๆ instance มีค่าเหมือนกัน ชี้ที่เดียวกันใน Memory หากมีการเปลี่ยนแปลงที่ Object1 ก็จะเปลี่ยนเหมือนกันทุกตัว

Declaration Type of Instance

Person john; john = new Person();

เราอาจจะอธิบายโค้ดนี้ด้วยการบอกว่า “สร้าง john เป็นตัวแปร type Person แล้ว สร้าง object แล้วให้ john เป็น instance ชี้ไปยัง address ของ object ที่สร้างขึ้น”

แต่จริงๆแล้วก่อนสร้าง instance ตัวแปร john ก็ไม่ต่างจากตัวแปร type Animal, World หรือ ชื่อของ Class อื่นๆ เพราะว่า สุดท้ายแล้วมันก็แค่ pointer ชี้ไปยัง address ของ object แต่อย่างไรก็ตาม การประกาศ type เป็นการช่วยในการจัดการข้อมูล ซึ่งเป็นหน้าที่หนึ่งที่ complier ช่วยทำให้ เช่น จะเกิด error หากเราพยายาม assign address ของ class Animal ไปใส่ใน instance type Table.

If you want to become a good developer, its important to understand that no computer environment ever works based on philosophic ideals.

Credit

Lastest edit: 2020-12-18