Introduction
Encapsulation helps keep data safe and hides details inside a class. It makes programs easier to understand and change.
Jump into concepts and practice - no test required
Encapsulation helps keep data safe and hides details inside a class. It makes programs easier to understand and change.
class ClassName { private int data; // hidden data public int GetData() { return data; } public void SetData(int value) { if (value >= 0) // control access data = value; } }
private means the data is hidden from outside the class.
Use public methods to safely get or set the data.
class BankAccount { private double balance; public double GetBalance() { return balance; } public void Deposit(double amount) { if (amount > 0) balance += amount; } }
class Person { private string name; public string Name { get { return name; } set { if (!string.IsNullOrEmpty(value)) name = value; } } }
This program shows how encapsulation protects the speed value. It only allows valid speeds between 0 and 200.
using System; class Car { private int speed; public int Speed { get { return speed; } set { if (value >= 0 && value <= 200) speed = value; } } } class Program { static void Main() { Car myCar = new Car(); myCar.Speed = 150; // set speed safely Console.WriteLine($"Car speed is {myCar.Speed} km/h"); myCar.Speed = -10; // invalid speed, ignored Console.WriteLine($"Car speed after invalid set: {myCar.Speed} km/h"); } }
Encapsulation helps avoid bugs by controlling how data changes.
It makes your code safer and easier to maintain.
Encapsulation hides data inside classes to protect it.
Use private fields and public methods or properties to control access.
This keeps your program organized and easier to fix or improve.
private comes before the type and variable name.private int age; which is correct syntax for a private field.class Person {
private string name = "Alice";
public string GetName() {
return name;
}
}
var p = new Person();
Console.WriteLine(p.GetName());name is private but accessible inside the class. The method GetName() returns the value of name.GetName()p.GetName() returns "Alice", which is printed.class BankAccount {
private double balance;
public double GetBalance() {
return balance;
}
public void SetBalance(double amount) {
balance = amount;
}
}
var account = new BankAccount();
account.balance = 1000;account.balance = 1000; but balance is private, so this causes an error.SetBalance.