CHAPTER 5 UNDERSTANDING ENCAPSULATION
Let’s see each of our options, beginning with the concept of static data.
Note You will examine the role of static properties later in this chapter, during our examination of properties
themselves.
Defining Static Field Data
Most of the time when designing a class, you define data as instance-level data; said another way, as
nonstatic data. When you define instance-level data, you know that every time you create a new object,
the object maintains its own independent copy of the data. In contrast, when you define static data of a
class, the memory is shared by all objects of that category.
To see the distinction, create a new Console Application project named StaticDataAndMembers.
Now, insert a new class into your project named SavingsAccount. Begin by defining a point of instancelevel data (to model the current balance) and a custom constructor to set the initial balance:
// A simple savings account class.
class SavingsAccount
{
// Instance-level data.
public double currBalance;
}
public SavingsAccount(double balance)
{
currBalance = balance;
}
When you create SavingsAccount objects, memory for the currBalance field is allocated for each
object. Thus, you could create five different SavingsAccount objects, each with their own unique balance.
Furthermore, if you change the balance on one account, the other objects are not affected.
Static data, on the other hand, is allocated once and shared among all objects of the same class
category. Add a static point of data named currInterestRate to the SavingsAccount class, which is set to
a default value of 0.04:
// A simple savings account class.
class SavingsAccount
{
// Instance-level data.
public double currBalance;
// A static point of data.
public static double currInterestRate = 0.04;
public SavingsAccount(double balance)
{
currBalance = balance;
}
}
178