CHAPTER 5 UNDERSTANDING ENCAPSULATION
If you were to create three instances of SavingsAccount in Main() as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Static Data *****\n");
SavingsAccount s1 = new SavingsAccount(50);
SavingsAccount s2 = new SavingsAccount(100);
SavingsAccount s3 = new SavingsAccount(10000.75);
Console.ReadLine();
}
the in-memory data allocation would look something like Figure 5-3.
Figure 5-3. Static data is allocated once and shared among all instances of the class
Here, our assumption is that all saving accounts should have the same interest rate. Because static
data is shared by all objects of the same category, if you were to change it in any way, all objects will
“see” the new value the next time they access the static data, as they are all essentially looking at the
same memory location. To understand how to change (or obtain) static data, we need to consider the
role of static methods.
Defining Static Methods
Let’s update the SavingsAccount class to define two static methods. The first static method
(GetInterestRate()) will return the current interest rate, while the second static method
(SetInterestRate()) will allow you to change the interest rate:
// A simple savings account class.
class SavingsAccount
{
// Instance-level data.
public double currBalance;
// A 7FF