© Khmer Angkor Academy - sophearithput168

Encapsulation

Encapsulation (ការហ៊ុមព័ទ្ធទិន្នន័យ) ក្នុង Java

🔒 Encapsulation គឺជាអ្វី?

Encapsulation គឺការរួមបញ្ចូលទិន្នន័យ (data) និង methods ដែលធ្វើការលើទិន្នន័យនោះ ក្នុង unit តែមួយ (class) ហើយលាក់ implementation detailsពី outside world។

ឧទាហរណ៍ក្នុងជីវិតពិត:

  • ថង់: ទុកលុយនៅខាងក្នុង មិនឱ្យគេឃើញ ចូលបានតាម zip តែប៉ុណ្ណោះ
  • ATM: ប្រព័ន្ធខាងក្នុងលាក់ អ្នកដកលុយតាម interface តែប៉ុណ្ណោះ
  • ឡាន: Engine ខាងក្នុងស្មុគស្មាញ បើកបរតាម steering & pedals តែប៉ុណ្ណោះ

📚 ហេតុអ្វីត្រូវការ Encapsulation?

  1. Data Hiding: បាំងទិន្នន័យសំខាន់
  2. Security: ការពារទិន្នន័យពី unauthorized access
  3. Control: គ្រប់គ្រងការផ្លាស់ប្តូរទិន្នន័យ
  4. Flexibility: ផ្លាស់ប្តូរ implementation ដោយមិនប៉ះពាល់ outside code
  5. Maintainability: កូដងាយ maintain និង debug
  6. Read-only or Write-only: បង្កើត properties ពិសេស

🔑 របៀបធ្វើ Encapsulation

  1. ធ្វើ instance variables ជា private
  2. ផ្តល់ public getter methods (អាន value)
  3. ផ្តល់ public setter methods (កំណត់ value)
  4. Validate data នៅក្នុង setter methods

✅ ឧទាហរណ៍មូលដ្ឋាន

// ❌ មិនល្អ - គ្មាន encapsulation
class Person {
    public String name;
    public int age;
}

Person p = new Person();
p.age = -50;  // Invalid! ប៉ុន្តែមិនមានការពារ


// ✅ ល្អ - មាន encapsulation
class Person {
    private String name;  // លាក់
    private int age;      // លាក់
    
    // Getter
    public String getName() {
        return name;
    }
    
    // Setter with validation
    public void setName(String name) {
        if (name != null && !name.isEmpty()) {
            this.name = name;
        } else {
            System.out.println("Invalid name!");
        }
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        if (age > 0 && age < 150) {
            this.age = age;
        } else {
            System.out.println("Invalid age!");
        }
    }
}

Person p = new Person();
p.setAge(25);    // ✅ Valid
p.setAge(-50);   // ❌ Rejected by validation

📊 Access Modifiers

Modifier Class Package Subclass World ប្រើសម្រាប់
private Data hiding
default Package-private
protected Inheritance
public API/Interface
Java Code
Click "Run" to execute the Java code

🎯 Getter & Setter Methods

📖 Getter Methods (Accessor)

ប្រើដើម្បីអានតម្លៃរបស់ private variables។

Naming Convention:

  • boolean: is + PropertyName (isActive, isValid)
  • Other types: get + PropertyName (getName, getAge)
class Student {
    private String name;
    private int age;
    private boolean active;
    
    // Getters
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public boolean isActive() {  // boolean = is___
        return active;
    }
}

✏️ Setter Methods (Mutator)

ប្រើដើម្បីកំណត់តម្លៃរបស់ private variables។

Naming Convention:

  • set + PropertyName (setName, setAge)
class Student {
    private String name;
    private int age;
    
    // Setters with validation
    public void setName(String name) {
        if (name != null && name.length() > 0) {
            this.name = name;
        }
    }
    
    public void setAge(int age) {
        if (age >= 0 && age <= 150) {
            this.age = age;
        }
    }
}

🎨 ប្រភេទ Properties

Type Getter Setter ប្រើប្រាស់
Read-Write អាន និង សរសេរ
Read-Only អានតែប៉ុណ្ណោះ
Write-Only សរសេរតែប៉ុណ្ណោះ (rare)

🔒 Read-Only Property

class Product {
    private final String id;  // final = cannot change
    private String name;
    
    public Product(String id, String name) {
        this.id = id;
        this.name = name;
    }
    
    // Getter only - Read-only
    public String getId() {
        return id;
    }
    
    // No setter for id!
    
    // Read-Write property
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}
Java Code
Click "Run" to execute the Java code

💡 Best Practices & Real-World Examples

✅ Encapsulation Best Practices

  1. Always use private: Instance variables ត្រូវតែ private
  2. Validate in setters: ពិនិត្យទិន្នន័យមុនពេល set
  3. Immutable when possible: ប្រើ final សម្រាប់ constants
  4. Return copies: Return copy of mutable objects (arrays, collections)
  5. Meaningful names: Getter/Setter ត្រូវមានឈ្មោះច្បាស់
  6. Don't expose collections: Return unmodifiable collections

🎯 Real-World Banking Example

class BankAccount {
    private String accountNumber;
    private String holderName;
    private double balance;
    private boolean active;
    
    public BankAccount(String accountNumber, String holderName) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = 0.0;
        this.active = true;
    }
    
    // Read-only
    public String getAccountNumber() {
        return accountNumber;
    }
    
    // Read-Write with validation
    public String getHolderName() {
        return holderName;
    }
    
    public void setHolderName(String name) {
        if (name != null && name.length() >= 3) {
            this.holderName = name;
        } else {
            System.out.println("Invalid name!");
        }
    }
    
    // Read-only (សម្លាប់មិនផ្តល់ setter)
    public double getBalance() {
        return balance;
    }
    
    // Controlled modification តាម methods
    public void deposit(double amount) {
        if (amount > 0 && active) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Invalid deposit!");
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance && active) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Invalid withdrawal!");
        }
    }
    
    public boolean isActive() {
        return active;
    }
    
    public void closeAccount() {
        if (balance == 0) {
            active = false;
            System.out.println("Account closed");
        } else {
            System.out.println("Cannot close! Balance: $" + balance);
        }
    }
}

⚠️ Common Mistakes

កំហុស ហេតុផល ដំណោះស្រាយ
public variables គ្មានការពារ, ពិបាក maintain ប្រើ private + getter/setter
No validation អាច set invalid data Validate នៅក្នុង setter
Return mutable reference អាចកែពីខាងក្រៅ Return copy ឬ immutable
Too many getters/setters Class ធ្វើជា data structure បន្ថែម business logic methods

💡 ប្រយោជន៍ពិតប្រាកដ

  • Security: Password, credit card ត្រូវ private
  • Validation: Age, email, phone number ត្រូវ validate
  • Logging: អាច log នៅពេល access/modify data
  • Lazy initialization: Create objects នៅពេលត្រូវការ
  • Change notification: Notify observers នៅពេល data ផ្លាស់ប្តូរ
  • Backward compatibility: ផ្លាស់ប្តូរ internal ដោយមិន break API
Java Code
Click "Run" to execute the Java code