CHAPTER 5 UNDERSTANDING ENCAPSULATION
Note To be more specific, members of a class that represent an object’s state should not be marked as public.
As you will see later in this chapter, public constants and public read-only fields are a-okay.
Encapsulation provides a way to preserve the integrity of an object’s state data. Rather than defining
public fields (which can easily foster data corruption), you should get in the habit of defining private
data, which is indirectly manipulated using one of two main techniques:
•
Define a pair of public accessor (get) and mutator (set) methods.
•
Define a public .NET property.
Whichever technique you choose, the point is that a well-encapsulated class should protect its data
and hide the details of how it operates from the prying eyes of the outside world. This is often termed
black box programming. The beauty of this approach is that an object is free to change how a given
method is implemented under the hood. It does this without breaking any existing code making use of it,
provided that the parameters and return values of the method remain constant.
Encapsulation Using Traditional Accessors and Mutators
Over the remaining pages in this chapter, you will be building a fairly complete class that models a
general employee. To get the ball rolling, create a new Console Application named EmployeeApp and
insert a new class file (named Employee.cs) using the Project Add class menu item. Update the Employee
class with the following fields, methods, and constructors:
class Employee
{
// Field data.
private string empName;
private int empID;
private float currPay;
// Constructors.
public Employee() {}
public Employee(string name, int id, float pay)
{
empName = name;
empID = id;
currPay = pay;
}
// Methods.
public void GiveBonus(float amount)
{
currPay += amount;
}
public void DisplayStats()
{
Console.WriteLine("Name: {0}", empName);
191