Object-oriented programming (OOP) เป็น programming paradigm ที่ฐานบน concept ของ "objects" ซึ่งอาจมี data ในรูป fields (attributes) และ code ในรูป procedures (methods) ตัวอย่าง person เป็น object ที่มี properties: height, gender, age ฯลฯ และ methods: move, talk ฯลฯ
Object (วัตถุ)
หน่วยพื้นฐานของ OOP คือ data และ functions ที่ operate บน data ถูก bundled รวมกันเป็น unit เรียกว่า object
Class (คลาส)
เมื่อคุณ define class คุณกำหนด blueprint สำหรับ object ไม่ได้ define data จริง แต่ define ว่า class name หมายถึงอะไร คือ object ของ class จะประกอบด้วยอะไร และ operations ใดสามารถทำได้
OOP มี 4 basic concepts ที่เป็นพื้นฐาน:
- Abstraction (นามธรรม) – ให้ข้อมูลจำเป็นอย่างเดียวกับ outside world ซ่อน background details ตัวอย่าง web server ซ่อนการ process data user เพียง hit endpoints ได้ data กลับ
- Encapsulation (การห่อหุ้ม) – กระบวนการ bind data members (variables, properties) และ member functions (methods) เป็น single unit ยังเป็นวิธี restrict access ไปยัง properties/components ตัวอย่างที่ดีที่สุดคือ class
- Inheritance (การสืบทอด) – ความสามารถสร้าง class ใหม่จาก class ที่มีอยู่ เรียกว่า Inheritance ใช้ inheritance สร้าง Child class จาก Parent class 繼承 properties และ methods ของ parent และมี properties/methods เพิ่มเติมของตัวเอง เช่น class Vehicle มี Color, Price สร้าง Bike และ Car ที่มี properties นั้นและเพิ่ม specialized properties เช่น car มี numberOfWindows แต่ bike ไม่มี methods เหมือนกัน
- Polymorphism (พหุรูป) – คำว่า polymorphism หมายถึง having many forms ปกติเกิดเมื่อมี hierarchy ของ classes และ related by inheritance C++ polymorphism หมายถึง call to member function จะ execute function ต่างกันไปขึ้นอยู่กับ type ของ object ที่ invoke function