Encapsulation (การห่อหุ้ม) คือการรวม Data (Fields) และ Behavior (Methods) ไว้ใน Class เดียวกัน และควบคุมการเข้าถึงผ่าน Access Specifiers
Access Specifiers
| Specifier | Visibility |
|---|---|
| public | ทุกที่ |
| private | ใน Class เดียวกัน (Default) |
| protected | Class เดียวกัน + Derived Classes |
| internal | Assembly เดียวกัน |
| protected internal | Protected OR Internal |
| private protected | Protected AND Internal (C# 7.2+) |
ตัวอย่าง: ใช้ private Fields + Public Properties/Methods
using System;
namespace RectangleApplication
{
class Rectangle
{
// Private Fields - ซ่อนข้อมูล
private double length;
private double width;
// Public Methods - Interface สำหรับเข้าถึง
public void AcceptDetails()
{
length = 10;
width = 15;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.AcceptDetails();
r.Display();
Console.ReadLine();
}
}
}
ผลลัพธ์
Length: 10 Width: 15 Area: 150
Properties (Modern Encapsulation)
class Rectangle
{
private double _length;
public double Length
{
get => _length;
set
{
if (value <= 0)
throw new ArgumentException("Length must be positive");
_length = value;
}
}
}
ประโยชน์ของ Encapsulation
- Data Hiding - ซ่อน Implementation Details
- Validation - ตรวจสอบค่าก่อน Set (ใน Setter)
- Flexibility - เปลี่ยน Internal Implementation โดยไม่กระทบ Caller
- Control - Read-only, Write-only, Lazy Loading ได้