230 likes | 368 Views
Chapter 4. Writing Classes. Figures from Lewis, “C# Software Solutions”, Addison Wesley. Topics. Adding a Class to a Project Defining a Class Attributes Methods Using a Class Visibility. Multiple Classes in a Project. You’ve seen projects with many classes
E N D
Chapter 4 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley
Topics • Adding a Class to a Project • Defining a Class • Attributes • Methods • Using a Class • Visibility
Multiple Classes in a Project • You’ve seen projects with many classes • XNA projects can (and often do) have multiple classes… one for each game element • Can add classes to our project • Keep them all in one file (~bad choice) • One class per file (better choice)
Addingto aProject Right-click project Select Add | Add New Item…
Using the Class • Before we define the Die class, let’s use it • Remember that OOP allows us to ignore the “guts” and just presume it works • There are 3+ people involved • The writer of the class (knows what the “guts” are) • The user of the class, writing the main program (knows his code, but doesn’t know the class “guts”) • The user of the program – sees the interface, doesn’t see program code at all
The Die • At this point, what do you know about Die from the code? • You can “Roll()” it • It has “FaceValue” • Can call “SetFaceValue()” • Can call “GetFaceValue()” • Now let’s look at the guts…
The “User” of a Class • Recall we don’t want to have to expose the “guts” • But we do need to tell a user of our class what it can do and what they have access to • Define the API of the class
Visibility • OO motivation: protection/security • We need a way of selectively “publishing” parts of a class and “hiding” other parts of the class • Public & private
Visibility Example class BMW_Z4 { private int ModelYear; public string LicensePlate; private bool TopUp; public void Drive() { Console.WriteLine("Roadin’ and Rockin’"); } public void OpenTop() { TopUp = false; } } Note the visibility (attributes will usually be private) Method aretypically public
Object Method & Attribute Visibility BMW_Z4 myCar; myCar = new BMW_Z4(); myCar.LicensePlate = "BMR4ME"; myCar.ModelYear = 2004; myCar.Drive(); myCar.OpenTop(); myCar.Drive(); Illegal b/c private
Interacting with Objects • Keep private/public visibility as needed