Defining Classes

When you define a new class, you define the characteristics of all objects of that class, as well as their behaviors. For example, if you create your own windowing operating system, you might want to create screen widgets (known as controls in Windows). One control of interest might be a listbox, a control that is very useful for presenting a list of choices to the user and enabling the user to select from the list.

Listboxes have a variety of characteristics: height, width, location, and text color, for example. Programmers have also come to expect certain behaviors of listboxes—they can be opened, closed, sorted, and so on.

Object-oriented programming allows you to create a new type, ListBox, which encapsulates these characteristics and capabilities.

To define a new type or class, you first declare it and then define its methods and fields. You declare a class using the class keyword. The complete syntax is:


[attributes] [access-modifiers] class identifier [:base-class]
{class-body}

Attributes are used to provide special metadata about a class (that is, information about the structure or use of the class). You won’t need to use attributes in this book, but you may run into them if you venture into more advanced topics.

Access modifiers are discussed later in this chapter. (Typically, your classes will use the keyword public as an access modifier.)

The identifier is the name of the class that you provide. Typically, C# classes are named with nouns (Dog, Employee, ListBox). The naming convention (not required, but strongly encouraged) is to use Pascal notation. In Pascal notation, you don’t use underbars or hyphens, but if the name has two words (Golden Retriever), you push the two words together, each word beginning with an uppercase letter (GoldenRetriever).

As we mentioned earlier, inheritance is one of the pillars of object-oriented programming. The optional base class is key to inheritance, as we’ll explain in Chapter 11.

The member definitions that make up the class body are enclosed by open and closed curly braces ({}):

class Dog
{
   int age; // the dog's age
   int weight; // the dog's weight
   Bark( ) { //... }
   Eat( ) { // ... }
}

Methods within the class definition of Dog define all the things a dog can do. The fields (member variables) such as age and weight describe all of the dog’s attributes or state.

Instantiating Objects

To make an actual instance, or object, of the Dog class, you must declare the object and allocate memory for the object. These two steps combined are necessary to create, or instantiate, the object. Here’s how you do it.

First, you declare the object by writing the name of the class (Dog) followed by an identifier (name) for the object or instance of that class:

Dog milo; // declare milo to be an instance of Dog

This is not unlike the way you create a local variable; you declare the type (in this case, Dog), followed by the identifier (milo). Notice also that by convention, the identifier for the object is written in Camel notation. Camel notation is just like Pascal notation except that the very first letter is lowercase. Thus, a variable or object name might be myDog, designatedDriver, or plantManager.

The declaration alone doesn’t actually create an instance, however. To create an instance of a class, you must also allocate memory for the object using the keyword new:

milo = new Dog( ); // allocate memory for milo

You can combine the declaration of the Dog type with the memory allocation into a single line:

Dog milo = new Dog( );

This code declares milo to be an object of type Dog and also creates a new instance of Dog. You’ll see what the parentheses are for in “Constructors” later in this chapter.

In C#, everything happens within a class. No methods can run outside a class, not even Main( ). The Main( ) method is the entry point for your program; it is called by the operating system, and it is where execution of your program begins. Typically, you’ll create a small class to house Main( ), because like every method, Main( ) must live within a class. Some of the examples in this book use a class named Tester to house Main( ):

public class Tester
{
   public static void Main( )
   {
      //...
   }
}

Even though Tester was created to house the Main( ) method, you’ve not yet instantiated any objects of type Tester. To do so, you would write:

Tester myTester = new Tester( ); // instantiate an object of type Tester

As you’ll see later in this chapter, creating an instance of the Tester class allows you to call other methods on the object you’ve created (myTester).

Creating a Box Class

We’ll start out with a very simple class—a three-dimensional box. The internal state of the box should keep track of the length, width, and height of the box. You probably also want some way to show the box to the user. In a graphical environment, you would probably draw the box, but because we’re working with console applications, we’ll compromise and just output the dimensions.

You might implement such a class by defining a single method and three variables, as shown in Example 7-1.

Example 7-1. The Box class is a very simple class with just three member fields and one method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_7_1_ _ _ _The_Box_Class
{
   public class Box
   {
      // private variables
      private int length;
      private int width;
      private int height;

      // public methods
      public void DisplayBox( )
      {
         Console.WriteLine("Stub for displaying the box.");
      }
   }

   public class Tester
   {
      static void Main( )
      {
         Box boxObject = new Box( );
         boxObject.DisplayBox( );
      }
   }
}

This code creates a new user-defined type: Box. The Box class definition begins with the declaration of a number of member variables: Length, Width, and Height.

The keyword private indicates that these values can be accessed only by methods of this class. The private keyword is an access modifier, explained later in this chapter.

Tip

Many C# programmers prefer to put all of the member fields together, either at the very top or at the very bottom of the class declaration, though that is not required by the language.

The only method declared within the Box class is the method DisplayBox( ). The DisplayBox( ) method is defined to return void; that is, it will not return a value to the method that invokes it. For now, the body of this method has been “stubbed out.”

Stubbing out a method is a temporary measure you might use when you first write a program to allow you to think about the overall structure without filling in every detail when you create a class. When you stub out a method body, you leave out the internal logic and just mark the method, perhaps with a message to the console:

public void DisplayBox( )
{
   Console.WriteLine("Stub for displaying the box.");
}

After the closing brace, a second class, Tester, is defined. Tester contains our now familiar Main( ) method. In Main( ), an instance of Box is created, named boxObject:

Box boxObject = new Box( );

Tip

Technically, an unnamed instance of Box is created in an area of memory called the heap, and a reference to that object is returned and used to initialize the Box reference named boxObject. Because that is cumbersome, we’ll simply say that a Box instance named boxObject was created.

Because boxObject is an instance of Box, Main( ) can make use of the DisplayBox( ) method defined for objects of that type and can call it to display the dimensions of the box:

boxObject.DisplayBox( );

You invoke a method on an object by writing the name of the object (boxObject) followed by the dot operator (.), the method name (DisplayBox), and the parameter list in parentheses (in this case, the list is empty). You’ll see how to pass in values to initialize the member variables in “Constructors” later in this chapter.

Access Modifiers

An access modifier determines which class methods—including methods of other classes—can see and use a member variable or method within a class. Table 7-1 summarizes the C# access modifiers.

Table 7-1. Access modifiers

Access modifier

Restrictions

public

No restrictions. Members that are marked public are visible to any method of any class.

private

The members in class A that are marked private are accessible only to methods of class A.

protected

The members in class A that are marked protected are accessible to methods of class A and also to methods of classes derived from class A. The protected access modifier is used with derived classes, as explained in Chapter 11.

internal

The members in class A that are marked internal are accessible to methods of any class in A’s assembly. An assembly is a collection of files that appear to the programmer as a single executable or DLL.

protected internal

The members in class A that are marked protected internal are accessible to methods of class A, to methods of classes derived from class A, and also to any class in A’s assembly. This is effectively protected or internal; there is no concept of protected and internal.

Public methods are part of the class’s public interface: they define how this class behaves. Private methods are “helper methods” used by the public methods to accomplish the work of the class. Because the internal workings of the class are private, helper methods need not (and should not) be exposed to other classes.

The Box class and its method DisplayBox( ) are both declared public so that any other class can make use of them. If DisplayBox( ) had been private, you wouldn’t be able to invoke DisplayBox( ) from any method of any class other than methods of Box itself. In Example 7-1, DisplayBox( ) was invoked from a method of Tester (not Box), and this was legal because both the class (Box) and the method (DisplayBox) were marked public.

Tip

It is good programming practice to explicitly set the accessibility of all methods and members of your class. Although you can rely on the fact that class members are declared private by default, making their access explicit indicates a conscious decision and is self-documenting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset