C# > Object-Oriented Programming (OOP) > Encapsulation > Private Fields and Public Methods

Encapsulation Example: Bank Account

This code snippet demonstrates encapsulation using a BankAccount class in C#. Encapsulation is achieved by declaring the account balance as a private field and providing public methods to interact with it. This prevents direct access to the balance from outside the class and ensures data integrity by controlling how the balance is modified.

Code Snippet

The BankAccount class contains a private field _balance, which stores the account balance. It's private, meaning it's only accessible from within the BankAccount class itself. The class provides three public methods: GetBalance, Deposit, and Withdraw. These methods are the only way to interact with and modify the account balance from outside the class. The Deposit and Withdraw methods include basic validation to ensure data integrity (e.g., preventing negative deposits or withdrawals exceeding the balance).

public class BankAccount
{
    private decimal _balance;

    public BankAccount(decimal initialBalance)
    {
        _balance = initialBalance;
    }

    public decimal GetBalance()
    {
        return _balance;
    }

    public void Deposit(decimal amount)
    {
        if (amount > 0)
        {
            _balance += amount;
        }
        else
        {
            Console.WriteLine("Deposit amount must be positive.");
        }
    }

    public void Withdraw(decimal amount)
    {
        if (amount > 0 && amount <= _balance)
        {
            _balance -= amount;
        }
        else
        {
            Console.WriteLine("Insufficient funds or invalid withdrawal amount.");
        }
    }
}

public class Example
{
    public static void Main(string[] args)
    {
        BankAccount account = new BankAccount(1000);
        Console.WriteLine("Initial Balance: " + account.GetBalance());
        account.Deposit(500);
        Console.WriteLine("Balance after deposit: " + account.GetBalance());
        account.Withdraw(200);
        Console.WriteLine("Balance after withdrawal: " + account.GetBalance());

        // Attempting to directly access the private field will result in a compilation error.
        // account._balance = -1000; // This line would cause an error.
    }
}

Concepts Behind the Snippet

Encapsulation is one of the four fundamental principles of object-oriented programming (OOP). It involves bundling data (fields) and methods that operate on that data within a single unit (a class). By controlling access to the data through public methods, encapsulation helps to hide the internal implementation details of the class and prevent unintended modifications to its state. This promotes modularity, maintainability, and data integrity.

Real-Life Use Case

Encapsulation is heavily used in software development. Think about managing user profiles. Sensitive information like passwords and personal details are kept private within the user class. Public methods like ChangePassword, UpdateProfile allow controlled access and modification of this data, ensuring that the data adheres to specific business rules and security policies.

Best Practices

  • Make fields private as much as possible.
  • Provide public methods (getters and setters) to control access to the fields.
  • Implement validation logic within the public methods to ensure data integrity.
  • Avoid exposing internal implementation details of the class.

Interview Tip

When discussing encapsulation, emphasize its role in data hiding and data integrity. Explain how it prevents direct access to class members, allowing you to control how the state of an object is modified. Be prepared to provide real-world examples of encapsulation in action.

When to Use Them

Use private fields and public methods whenever you want to control access to the data within a class and ensure that it is modified in a safe and predictable manner. This is especially important when dealing with sensitive data or when you need to enforce specific business rules.

Memory Footprint

Encapsulation itself doesn't significantly impact memory footprint. The memory usage depends on the data types of the fields within the class. However, by properly managing the lifetime of objects and avoiding unnecessary data duplication, you can minimize the overall memory footprint of your application.

Alternatives

While encapsulation is a core OOP principle, alternatives like data classes with public properties exist. However, these approaches sacrifice the control and data integrity benefits that encapsulation provides. Data classes are often used for simple data transfer objects (DTOs) where encapsulation is less critical.

Pros

  • Data Hiding: Prevents direct access to internal data.
  • Data Integrity: Ensures data is modified in a controlled manner.
  • Modularity: Promotes loose coupling between classes.
  • Maintainability: Makes code easier to understand and modify.

Cons

  • Increased Complexity: Can add some overhead in terms of code complexity.
  • Potential Performance Overhead: Method calls can have a slight performance impact compared to direct field access. (Usually negligible).

FAQ

  • What is the purpose of using private fields?

    Private fields ensure that the internal data of a class is protected from direct access or modification from outside the class. This helps maintain data integrity and prevents unintended side effects.
  • Why use public methods to access private fields?

    Public methods provide a controlled interface for interacting with the private fields of a class. This allows you to implement validation logic, enforce business rules, and hide the internal implementation details of the class.
  • Can I access a private field using reflection?

    Yes, but it bypasses the intention of encapsulation and should be avoided in normal circumstances. Reflection can be useful in specific scenarios like testing or debugging, but it should be used with caution.