Chapter 6 OOP Creating ObjectOriented Programs Programming in
Chapter 6 OOP: Creating Object-Oriented Programs Programming in C#. NET © 2003 by The Mc. Graw-Hill Companies, rights reserved. © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Objectives • Use the object-oriented terminology correctly • Create a two-tier application that separates the user interface from the business logic • Differentiate between a class and an object • Create a class that has properties and methods • Use property accessor methods to set and retrieve private properties of a class 2 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Objectives cont. • Declare object variables and assign values to the properties with a constructor or property accessor method • Instantiate an object in a project using your class • Differentiate between static members and instance members • Understand the purpose of the constructor and destructor methods • Inherit a new class form your own class • Apply visual inheritance by deriving a form from another form 3 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Object-Oriented Programming • Objects have properties and methods and generate events • Classes for all objects are predefined or defined by a programmer • Object-oriented programming (OOP) is currently the most accepted style of programming 4 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Objects • Create a new object type by creating a new class with properties and methods – Properties are characteristics – Methods are actions • To create a new object you instantiate an object of the class • The new object is an instance of the class • To call a method, refer to Object. Method 5 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Object-Oriented Terminology • Encapsulation is the combination of characteristics of an object along with its behaviors – One “package” holds the definition of all properties, methods, and events – Cannot make up new properties or methods – Also called data hiding 6 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Object-Oriented Terminology cont. • Inheritance is the ability to create a new class from an existing class – Create a new class from an existing class to add or modify class variables and methods – Original class is the base class, superclass, or parent class – Inherited class is the subclass, derived class, or child class 7 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Object-Oriented Terminology cont. • In the statement public class Form 1 : System. Windows. Form the colon (: ) indicates inheritance, Systems. Windows. Forms is the base class and Form 1 is the derived class • The purpose of inheritance is reusability • Create a hierarchy of classes by placing common code in a base class then creating other derived classes from it 8 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Object-Oriented Terminology cont. • Polymorphism is the ability to take on many shapes or forms • Polymorphism allows methods with the same names to have different implementations • Polymorphism uses overloading and overriding • In overriding, a subclass has a method identically named in the base class, and the subclass method overrides the method in the base class 9 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Reusable Classes • A big advantage of object-oriented programming over traditional programming is the ability to reuse classes • Use a new class in multiple projects • Similar to working with built-in controls in the toolbox 10 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Multitier Applications • Each function of a multitier application is coded in a separate component • Three-tier applications include: – Presentation tier – Present the user interface – Business tier – Handle the data – Data tier – Retrieve and store data in a database • An “n-tier” application is the expansion of three-tier model 11 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Classes • Use the new keyword to create an instance of a class which is called instantiating an object • General form is new class. Name(); • Examples: Font My. Font = new Font(“Arial”, 12); message. Label. Font = My. Font; message. Label. Font = new Font(“Arial”, 12); 12 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Specifying a Namespace • A fully qualified name includes the complete namespace and class name – Example: System. Windows. Forms. Text. Box where System. Windows. Forms is the namespace • Entire namespace not required for System, System. Windows. Forms, and System. Drawing • Add a using statement at beginning of code file to specify the namespace to be used then only refer to class name 13 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Designing Your Own Class • Analyze the characteristics and behaviors that your object needs – Characteristics become properties – Behaviors become methods 14 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Property Blocks • Define private member variables to store values for the class • The class controls access to its properties through accessor methods in a property block – get accessor method used to retrieve a property value – set accessor method used to assign a value to a property • set statement uses value keyword to refer to incoming value for property • Property block must be public 15 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Property Blocks cont. • Property Block – General Form private Data. Type Member. Variable; public Data. Type Property Name { get { return Member. Variable; } set { //statements, such as validation Member. Variable = value; } } 16 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Read-Only Properties • Write a property block that contains only a get to create a read-only property private decimal dec. Extended. Price; public decimal Extended. Price { get { return dec. Extended. Price; } { 17 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Write-Only Properties • Write a property block that contains only a set to create a write-only property private decimal dec. Price; public decimal Price { set { dec. Price = value; } { 18 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Class Methods • Create methods of the new class by coding public methods within the class • Methods declared with private are available only within the class • Methods declared with public are available to external objects created from this or other classes 19 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Constructors and Destructors • A constructor is a method that executes automatically when an object is instantiated • A destructor is a method that executes automatically when an object is destroyed • A constructor has the same name as the class 20 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Constructors • Executes before any other code in the class • Must be public • Empty constructor automatically created when you add a new class to project • If class does not have a constructor, the compiler creates a method called the default constructor with an empty argument list 21 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Overloading the Constructor • Create overloaded methods in your class by giving the same name to multiple methods, each with a different argument list • A parameterized constructor requires arguments • Use this keyword to refer to the current class in the class code 22 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Creating a New Class – Step-by-Step In this step-by-step tutorial, you will create a new class to hold book sale information for R ‘n R. 1. 2. 3. 4. 5. 6. 7. 23 Begin the Project Begin a New Class Define the Class Properties Add the Property Blocks Add the Method Add the Constructor Add General Remarks © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Creating a New Object Using a Class • • Creating a class defines a new type but does not create any objects Two steps to create a new object of a class 1. Declare a variable for the new object 2. Instantiate the object using the new keyword • 24 Use public or private followed by the class name and identifier to refer to the object of the class © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Creating a New Object Using a Class cont. • Declare the variable private Book. Sale book. Sale. Object; • Create the object book. Sale. Object = new Book. Sale(); • Combine declaration and instantiation of an object in the same statement Book. Sale book. Sale. Object = new Book. Sale(); • Should enclose instantiation in try/catch block if converting and passing values from a textbox 25 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Defining and Using a New Object – Step-by-Step To continue the step-by-step tutorial for the Book. Sale class, the next step is to design the form for the user interface. The form has text boxes for the user to enter the title, quantity, and price, a menu choice to calculate the sale (the extended price), and another menu item to exit. 26 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Defining and Using a New Object – Step-by-Step cont. In the Calculate Sale event handler, you will create an instance of the Book. Sale class and assign the input values for title, quantity, and price to the properties of the Book. Sale object. The Extended. Price property in the Book. Sale class retrieves the amount of the sale, which appears in a label on the form. 27 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Defining and Using a New Object – Step-by-Step cont. Placing all calculations in a separate class is a good thing. You are seeing your first example of dividing a program into a Presentation tier and a Business tier. 1. 2. 3. 4. 5. 6. 28 Create the Form Add Comments Declare the New Object Write the Code Save Your Work Run the Project © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Single-Step the Execution • A quick and easy way to debug is to singlestep program execution • Must be in break time to single-step – Place a breakpoint in code – Run the program – When program stops at breakpoint, press the F 11 key to single-step through 29 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Instance Variables versus Static Variables • Instance members exist once for each object of a class • Static members exist once for all objects of a class • Methods, variables, and properties can be declared as instance or static • Access static members without instantiating an object of the class 30 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Instance Variables versus Static Variables cont. • Must reference static members with Class. Name. Property or Class. Name. Method • Use the static keyword to create a static member [public|private] static Datatype Variable. Name; [public|private] static Datatype Method. Name(Argument. List); • Must use static keyword on property block if you will retrieve the property without first creating an instance of the class 31 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Adding Static Properties to the Step-by-Step Tutorial You will now make the Book. Sale class calculate the total of all sales and a count of the number of sales. You will need static properties for the sales total and sales count in the class. Then on the form, you will add a menu option for Summary that displays the totals in a message box. 32 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Adding Static Properties to the Step-by-Step Tutorial cont. 1. 2. 3. 4. 5. 33 Add Static Properties to the Class Modify the Code to Calculate the Totals Modify the Form Test the Program Save This Version of the Program © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Destructors • Write processing to occur when an object goes out of scope in a destructor • Destructor is a method with the same name as the class preceded by a tilde (~) • Destructor method automatically calls the Object. Finalize method from the base class of the object • Destructor called as part of the garbage collection by the CLR 34 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Garbage Collection • Garbage collection feature of. NET CLR cleans up unused components • Garbage collector periodically checks for unreferenced objects and releases all memory and system resources used by the objects • Microsoft recommends you rely on garbage collection to release resources 35 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Inheritance • A new class can inherit from a. NET class or one of your own classes • Inheritance statement format: public class New. Class : Base. Class • Inheritance clause must follow the class header before any comments 36 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Overriding Methods • A new method overrides the base class method with the same name • Derived class will use the new method, not the method in the base class with the same name • To override a method in C# – Declare the original method with the virtual or abstract keyword – Declare the new method with the override keyword 37 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Overriding Methods cont. • Examples: – Base Class protected virtual decimal Calculated. Extended. Price() – Inherited Class protected overrride decimal Calculated. Extended. Price() • You can use the virtual, abstract, or override keywords on a method that can be overriden – Use virtual when writing a new method that has code – Use abstract for a method header for an empty method – Use override when the method is overriding a method in its base class 38 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Accessing Properties • Call the base class constructor from the derived-class constructor • After assigning values to properties in the base class, you can refer to the properties in the base class from the derived class • Read-only or write-only properties cannot be accessed by name from a derived class 39 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Adding Inheritance to the Step-by-Step Tutorial This continuation of the chapter step-by-step tutorial includes a new subclass, overriding a method, and adding a new property. 1. 2. 3. 4. 5. 6. 7. 40 Add the New Class Add the Constructor Add the New Property Add a Constant Override a Method Allow a Method to be Inherited Modify the Form to Use the Inherited Class © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Creating a Base Class Strictly for Inheritance • Include the abstract modifier in the class declaration of a base class that will be inherited and methods that will be overridden //Base Class public abstract class Base. Class { public abstract void Some. Method() { //No code allowed here } } 41 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Inheriting Form Classes • Visual inheritance is designing one form then inheriting any other forms from the first • Base class inherits from System. Windows. Form and new forms inherit from the base class • Include design elements and controls, and write methods and declare variables in the base class • Write methods in base class with virtual or abstract then write method with same name and override keyword in the subclass 42 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Create an Inherited Form Class 1. Select Project/Add Windows Form and enter name for new form; Modify inheritance clause to inherit from base form using project name as namespace or 2. Select Project/Add Inherited Form and type name of new form; Enter information into dialog box 43 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Coding for Events of an Inherited Class • You cannot double-click on an inherited control to open the event-handling method • Instead, you can either copy the method from the base class into the derived class as a start, or use the inherited event handler in the derived class 44 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Managing Multiclass Projects • Form classes must be in separate files • Multiple classes can be in one file • Each C# file automatically contains a namespace statement – View and modify namespace in the Project Properties dialog box – Modify the namespace property at the top of each existing file • Modify the namespace statement if you move or copy a class or form file to a new project or include a using statement in the class file 45 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Add an Existing Class File to a Project • It is best to place the class file in the project folder but not required • Select Project/Add Existing Item to add an existing file to a project • Modify the namespace statement in the file to match the project 46 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Displaying Values on a Different Form • Reference controls on another form using the identifier for the form instance • Write the form reference as Form. Instance. Control. Name. Property • If the form to which you refer is in a different namespace, you must also include a reference to the namespace or include a using statement 47 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Using the Object Browser • The Object Browser will show names of objects, properties, methods, events and constants for: – C# objects – your own objects – objects available from other applications • Choose View/Other Windows/Object Browser or drop down the window list from the View toolbar button • Choose libraries/namespaces in the Browse list • Icons represent properties, methods, events, constants, classes, and namespaces 48 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Examining C# and Your Own Classes • You can see what elements are defined in the class, what is the base class, and which properties, methods, and events are inherited • Double-click on a name in the Members list to jump to the definition of any property or method • Select a form in the Objects list and doubleclick on method name to view 49 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Your Hands-On Programming Example This program must calculate books sales for R ‘n R, with a discount of 15 percent for students. The project will use the Book. Sale and Student. Book. Sale classes developed in the chapter step-by-step. Create a project with multiple forms that have a shared design element. Include a main form, an About form, and a Summary form that displays the sales summary information. 50 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Your Hands-On Programming Example cont. Design a base form to use for inheritance and make the other three forms inherit from the base form. The About form and Summary form must have an OK button, which closes the form. The main form will have menus and no OK button. 51 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Summary • Objects have properties and methods and can trigger events. • Create a new class that can be used to create new objects. • Creating a new object is instantiating the object. The object is an instance of the class. • Encapsulation is the combination of the characteristics and behaviors of an item into a single class definition. • Polymorphism allows different classes of objects to have similarly named methods that behave differently. 52 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Summary cont. • Inheritance provides a means to derive a new class based on an existing class. • A big advantage of OOP is that classes can be reused in many applications. • Multitier applications separate functions into tiers. • Variables inside a class used to store properties should be private. • Use property blocks with accessor methods (get and set) to make properties of a class available outside the class. 53 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Summary cont. • Read-only properties have only a get accessor method. Write-only properties have only a set accessor method. • Public methods of a class are available to other objects of the class and other classes. • Use the new keyword to instantiate an object of a class. • A constructor is a method that executes automatically when an object is created. A destructor executes automatically when the object is destroyed. 54 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Summary cont. • A constructor method must be named the same as the class and may be overloaded. • A parameterized constructor requires arguments to create a new object. • Static members have one copy that is used by all objects of the class. Instance members have one copy for each instance of the object. • Garbage collection checks for and destroys unreferenced objects, and releases resources. • A subclass inherits all public and protected properties and methods of its base class. 55 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Summary cont. • To override a base class method, it must be declared as virtual or abstract, and the new method must use the override keyword. • Use visual inheritance to derive new forms from existing forms. • Each project has a default namespace. Modify the namespace statement at the top of existing files. • Refer to controls on a different form with form instance name, control name, and property. • Use Object Browser to view classes, properties, methods, events, and constants in all classes. 56 © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
- Slides: 56