Classes are the primary blocks of objectoriented programming. When writing applications, developers often attempt to solve a problem or problem domain, as it's often called. Problem domains can be broken up into pieces and each piece can be addressed with a class. Take the example program for this chapter. The purpose of the program is to maintain a list of tasks a to-do listand to display the list to the user as requested . We could write a class called ToDoItem to store each to-do item, and another class called ToDoList, to store an entire list of to-do items. The class definition serves as a factory for objects. Each object can represent a different entity in the application. In our example, the ToDoItem class tells the language what ToDoItem objects contain. It is up to the developer to create objects from that class by using the new operator in C#: ToDoItem item1 = new ToDoItem(); Classes have two main aspects: state and behavior. Those are two abstract terms that simply boil down to fields and functions. Fields are variables declared inside a class. They are used to store information about each object. In the case of the application for this chapter, we create objects of type ToDoItem to hold the information for each to-do item. Fields are used to store the information about each to-do item. For example, we can add a field to store the name of the task and one to store the description. Fields enable each item object produced from the ToDoItem class to represent a different item in the list ( Figure 2.43 ). On the other hand all we need is one object of type ToDoList to hold the collection of to-do items. This ToDoList class may have a single field that refers to a collection of ToDoItems. Figure 2.43. Each instance of the ToDoItem class can store its own item and description. If you don't set a reference variable equal to a new instance of the class or to another variable that already points to an object then the variable's value is null.
In addition to the class defining the state information for each object the developer defines the behavior for the class. This is done by adding functions that make sense when using a ToDoItem object or a ToDoList object. For example, the ToDoList object may have a function called Add and another function called Remove. A programmer can use these functions to add to-do items to the list or to remove them from the list. A to-do item may also have functions such as SetInfo. Classes are defined with the class keyword. To declare a class:
Tips
|