Access Modifiers
In this page:
Access Modifiers
Access modifiers (public, private, protected, internal) control which code can see a class member. public members are visible everywhere, private members only inside the declaring class, and protected members inside the class and its subclasses. Encapsulating fields as private and exposing them through public properties is a core OOP practice.
Warning: Class members are private by default in C# if you omit a modifier.
Example: Access Modifiers
using System;
class Account
{
private decimal balance;
public Account(decimal startingBalance)
{
balance = startingBalance;
}
public void Deposit(decimal amount)
{
balance += amount;
}
public decimal GetBalance()
{
return balance;
}
}
class Program
{
static void Main(string[] args)
{
Account acc = new Account(100);
acc.Deposit(50);
Console.WriteLine(acc.GetBalance());
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: