Free mag vol1 | Page 228

CHAPTER 5  UNDERSTANDING ENCAPSULATION Figure 5-1. Inserting a new C# class type Notice that these member variables are declared using the public access modifier. Public members of a class are directly accessible once an object of this type has been created. Recall the term “object” is used to describe an instance of a given class type created using the new keyword.  Note Field data of a class should seldom (if ever) be defined as public. To preserve the integrity of your state data, it is a far better design to define data as private (or possibly protected) and allow controlled access to the data via properties (as shown later in this chapter). However, to keep this first example as simple as possible, public data fits the bill. After you have defined the set of member variables that represent the state of the class, the next design step is to establish the members that model its behavior. For this example, the Car class will define one method named SpeedUp() and another named PrintState(). Update your class as so: class Car { // The 'state' of the Car. public string petName; public int currSpeed; // The functionality of the Car. public void PrintState() { Console.WriteLine("{0} is going {1} MPH.", petName, currSpeed); } 164