Module 6: Fundamentals of Object- Oriented Programming

Similar documents
Lab Answer Key for Module 1: Creating Databases and Database Files

Lab Answer Key for Module 8: Implementing Stored Procedures

Introduction To C#.NET

Module 4: Data Types and Variables

Advanced Programming Using Visual Basic 2008

Module 9: Validating User Input

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 6 Introduction to Defining Classes

Chapter 4 Defining Classes I

Module 3: Managing Groups

Programming in Visual Basic with Microsoft Visual Studio 2010

Chapter 1 Getting Started

Microsoft Exchange Server SMTPDiag

Short Notes of CS201

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

CS201 - Introduction to Programming Glossary By

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Introduction to Programming Using Java (98-388)

Module 2: Introduction to a Managed Execution Environment

More C++ : Vectors, Classes, Inheritance, Templates

CS313D: ADVANCED PROGRAMMING LANGUAGE

10. Abstract Data Types

Implementing Subprograms

C++ (Non for C Programmer) (BT307) 40 Hours

Building Multitier Programs with Classes

CLASSES AND OBJECTS IN JAVA

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Object-Oriented Programming in C# (VS 2015)

9/21/2010. Based on Chapter 2 in Advanced Programming Using Visual Basic.NET by Bradley and Millspaugh

CS313D: ADVANCED PROGRAMMING LANGUAGE

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CHAPTER 7 OBJECTS AND CLASSES

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Introduce C# as Object Oriented programming language. Explain, tokens,

CHAPTER 7 OBJECTS AND CLASSES

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

OBJECT ORIENTED PROGRAMMING USING C++

CS201 Some Important Definitions

CS313D: ADVANCED PROGRAMMING LANGUAGE

EEE-425 Programming Languages (2013) 1

Object Oriented Programming in C#

Introduction to Inheritance

Abstract Data Types and Encapsulation Concepts

Module 7: Automating Administrative Tasks

Module 3: Creating Objects in C#

Cpt S 122 Data Structures. Introduction to C++ Part II

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Object-Oriented Programming in C# (VS 2012)

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

Data Structures (list, dictionary, tuples, sets, strings)

And Even More and More C++ Fundamentals of Computer Science

Java Primer 1: Types, Classes and Operators

CMSC 4023 Chapter 11

Programming II (CS300)

Module 3-1: Building with DIRS and SOURCES

Programming II (CS300)

Programming II (CS300)

Module 8: Implementing Stored Procedures

STUDENT LESSON A5 Designing and Using Classes

Object-Oriented Programming

Hands-On Lab. Lab Manual HOL007 Understanding, Designing, and Refactoring Code Using the New Class Designer Tool in Microsoft Visual Studio 2005

CHECK PROCESSING. A Select Product of Cougar Mountain Software

Introduction to Managed Code

C11: Garbage Collection and Constructors

Exclaimer Signature Manager 2.0 Release Notes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Chapter 11. Abstract Data Types and Encapsulation Concepts

Imperative Languages!

CS112 Lecture: Defining Instantiable Classes

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Microsoft Dynamics GP. Extender User s Guide

EEE-425 Programming Languages (2013) 1

VARIABLES AND TYPES CITS1001

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

JAVA: A Primer. By: Amrita Rajagopal

Microsoft Exchange 2000 Server Mailbox Folder Structure. Technical Paper

Microsoft Dynamics GP Release Integration Guide For Microsoft Retail Management System Headquarters

CPS122 Lecture: Defining a Class

2559 : Introduction to Visual Basic.NET Programming with Microsoft.NET

EECS168 Exam 3 Review

An Introduction to C++

C#: framework overview and in-the-small features

Module 8: Building a Windows Forms User Interface

Android ATC Android Security Essentials Course Code: AND-402 version 5 Hands on Guide to Android Security Principles

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

Chapter 12: How to Create and Use Classes

Deploying Windows Server 2003 Internet Authentication Service (IAS) with Virtual Local Area Networks (VLANs)

CPS 506 Comparative Programming Languages. Programming Language

Transcription:

Module 6: Fundamentals of Object- Oriented Programming Table of Contents Module Overview 6-1 Lesson 1: Introduction to Object-Oriented Programming 6-2 Lesson 2: Defining a Class 6-10 Lesson 3: Creating a Class Instance 6-28 Lab: Fundamentals of Object-Oriented Programming 6-38 Lab Discussion 6-46

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links are provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for Webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2007 Microsoft Corporation. All rights reserved. Microsoft, Access, Active Directory, BizTalk, DirectX, Excel, IntelliSense, Internet Explorer, MSDN, Outlook, PowerPoint, SQL Server, Visual Basic, Visual C#, Visual C++, Visual J#, Visual Studio, Win32, Windows, Windows CardSpace, Windows NT, Windows Server, Windows Vista, and WinFX are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. Version 1.1

Module 6: Fundamentals of Object-Oriented Programming 6-1 Module Overview This module introduces object-oriented programming. It describes classes and how to define a class in Microsoft Visual C# and Microsoft Visual Basic. The module also describes how to create and use instances of a class in Microsoft.NET Framework applications. Objectives After completing this module, you will be able to: Describe the essential features of object-oriented programming. Define a class. Create a class instance.

6-2 Module 6: Fundamentals of Object-Oriented Programming Lesson 1: Introduction to Object-Oriented Programming This lesson introduces essential object-oriented programming concepts, such as classes and objects. It describes what member types you can define in a class and discusses the benefits of encapsulating details within a class. It also introduces the concept of overloading and describes how this makes classes easier to use. Objectives After completing this lesson, you will be able to: Describe classes and objects. Describe fields, properties, methods, and events. Describe the role of encapsulation in object-oriented programming. Describe the role of overloading in object-oriented programming.

Module 6: Fundamentals of Object-Oriented Programming 6-3 Classes and Objects Visual C# and Visual Basic are object-oriented programming languages and use classes and objects. When you create a Visual C# or Visual Basic application, you define classes that represent the main data types in your application. You must define a class before you can create objects of that data type. What Is a Class? A class is a blueprint that you can use to create objects. A class defines the characteristics of an object, such as the data that the object can contain and the operations that the object can perform. What Is an Object? An object is an instance of a class. If a class is a blueprint, an object is what you create from that blueprint. The class is the definition of an item; the object is the item itself. Note: The term instance is often used as an alternative to object. Example of Classes and Objects The blueprint for a house is like a class, and the house that you live in is like an object. In object-oriented programming, you might define a House class that specifies that all houses have an area, color, and height. You might then create a House object that has the area, color, and height values for your particular house.

6-4 Module 6: Fundamentals of Object-Oriented Programming Fields, Properties, Methods, and Events Classes contain members that represent the data and behavior of the class or objects of that class type. Classes in Visual C# and Visual Basic typically contain fields, properties, and methods. Classes can also contain events, especially those classes that represent graphical controls such as buttons and text boxes. What Is a Field? A field is a class member that represents a piece of data that the class needs to fulfill its design. You typically define fields as private members in a class. This prevents the fields from being accessed directly from outside the class. What Is a Property? A property is a class member that provides a flexible mechanism to read, write, or compute the values of a field. You can use properties as though they are public data members. However, they are actually special methods named accessors.

Module 6: Fundamentals of Object-Oriented Programming 6-5 When you define a property in a class in Visual C# or Visual Basic, you can provide accessors to get the property value, set the property value, or both. The following table describes the three types of property that you can define. Type of property Accessors Example properties in a BankAccount class Read-write get and set accessors A property to get and set the account holder name. Read-only get accessor A property to get the current account balance. Write-only set accessor A property to set the maximum allowable withdrawal. What Is a Method? A method is a class member that contains a code block and represents an action that the object or class can perform. Methods can access the fields in the class to fulfill their designated tasks. What Is an Event? An event is a class member that indicates something has happened to an object or class. Events provide a notification mechanism that enables you to respond to events and perform appropriate event-handling operations. Example of Fields, Properties, Methods, and Events A class that represents a calendar date might have the following members: Three integer fields: one for the month, one for the day, and one for the year. Properties to get and set each of these fields and additional properties to compute values such as the day of the year and whether the year is a leap year. Methods to increment the date by one day, by one month, and by one year. Events to indicate that some aspect of the date has changed.

6-6 Module 6: Fundamentals of Object-Oriented Programming What Is Encapsulation? Non-object-oriented programming languages such as C and COBOL consist of data, either in a database or in computer memory, and separate instructions for manipulating that data. These languages do not usually enforce any sort of relationship between the data and the code that manipulates the data. If any aspect of the data changes for example, if a year field is changed from two digits to four digits then you must change all of the code that uses that data. Because the code is not closely related to the data, changing the code can be difficult and time-consuming. Object-oriented programming languages support the concept of encapsulation, so that you can control the visibility and accessibility of data and implementation details in your application. What Is Encapsulation? Encapsulation is the ability of an object or class to hide its internal data and implementation details, making only the intended parts of the object or class programmatically accessible. Encapsulation is an essential object-oriented principle. For example, when you define a class, you should always define the fields as private members. This prevents external code from accessing the fields directly. The only way for external code to interact with an object or class is through a well-defined public interface, which typically consists of properties and methods in the class. Benefits of Encapsulation You can use encapsulation to hide information. When you hide information, such as the internal state and implementation information of an object, external code focuses on only the useful characteristics of the object. Encapsulation helps to protect the data in an

Module 6: Fundamentals of Object-Oriented Programming 6-7 object; external code can interact with the data in an object only through the members of the object that it has access to. For example, the internal mechanism of a telephone is hidden from users. The wires, switches, and other internal parts of a telephone are encapsulated by its cover and are inaccessible to users. You can also use encapsulation to easily change the implementation details of your application without the users of your object or class experiencing any change in the way they interact with the object or class.

6-8 Module 6: Fundamentals of Object-Oriented Programming What Is Overloading? When you add methods to a class, you must choose meaningful method names that accurately describe what the methods do. In many cases, you might want to define several alternative implementations for a method within a class, with different parameters for each version. Visual C# and Visual Basic enable you to assign the same name to each of these methods, provided each version of the method has a different number of parameters or different parameter types. What Is Overloading? Overloading is the ability to define several methods with the same name in the same class, provided each method has a different signature. The method signature includes the method name and its parameters. Therefore, you can define any number of overloaded versions of a method within a class, as long as each one has a different number of parameters or different parameter types. Tip: Overloaded methods typically contain similar code. To reduce duplication between overloaded methods, implement functionality in one version of the overloaded method and then invoke it from other overloaded methods where possible. Benefits of Overloading Overloading makes a class easier for class users to understand, because methods that perform the same task have the same name. This accentuates the common purpose of the overloaded methods and helps to make external code more consistent.

Module 6: Fundamentals of Object-Oriented Programming 6-9 Example of Overloading The.NET Framework class library uses overloading. For example, the MessageBox class has 21 overloaded versions of the Show method, letting you provide as much or as little information as you want when you display a message box in a Microsoft Windows application. The following code samples show how to invoke three versions of the Show method. MessageBox.Show("Hello World"); MessageBox.Show("This is the message", "This is the caption"); MessageBox.Show("Save changes?", "Sales App", MessageBoxButtons.YesNoCancel); MessageBox.Show("Hello World") MessageBox.Show("This is the message", "This is the caption") MessageBox.Show("Save changes?", "Sales App", MessageBoxButtons.YesNoCancel)

6-10 Module 6: Fundamentals of Object-Oriented Programming Lesson 2: Defining a Class This lesson describes how to define new classes in Visual C# and Visual Basic and how to add members such as fields, methods, and properties to a class. The lesson also describes how to add constructors to a class to initialize fields when you create a new object. Objectives After completing this lesson, you will be able to: Define a new class. Define access levels. Add fields and methods to a class. Add properties to a class. Add constructors to a class. Use namespaces to organize classes.

Module 6: Fundamentals of Object-Oriented Programming 6-11 How to Define a New Class You can use Microsoft Visual Studio to add a new class to a project. Typically, you place each class into a separate source file that has the same name as the class. Visual Studio 2005 generates template code in the source file for the new class. Adding a New Class to a Project To add a new class to a project, follow these steps: 1. In Solution Explorer, right-click the project name, point to Add, and then click Class. 2. In the Add New Item dialog box, enter a name for the source file that will contain the new class, and then click Add. 3. View the code for the generated class. Example If you have a Windows application named BankingSystem, and you specify BankAccount.cs or BankAccount.vb as the name of the source file for the new class, Visual Studio generates the following code. using System; using System.Collections.Generic; using System.Text; namespace BankingSystem class BankAccount

6-12 Module 6: Fundamentals of Object-Oriented Programming Public Class BankAccount End Class The following table describes the key differences between the generated code for the new class in Visual C# and Visual Basic. Code feature Visual C# source code Visual Basic source code Imported namespaces Class namespace Class accessibility The source file contains a series of using statements that explicitly import namespaces that you might need in your class. The source file explicitly indicates the namespace of the class, based on the default namespace defined in the project properties. The generated class definition does not initially have an access modifier. If you want the class to be public, add the public keyword before the class keyword. The project properties specify the namespaces that are imported by default into every source file. The project properties specify the root namespace that applies to all class definitions. The generated class definition initially has the Public access modifier.

Module 6: Fundamentals of Object-Oriented Programming 6-13 How to Define Access Levels When you design a class, it is important to consider the accessibility of the class and its members. For example, you must decide whether to make the class visible to the entire application or to restrict its accessibility to the current assembly. Similarly, you must decide a suitable access level for each member in the class. Visual C# and Visual Basic provide keywords known as access modifiers, which enable you to specify the access level for classes and their members. Access Modifiers in Visual C# and Visual Basic Visual C# and Visual Basic support five access levels. The following table shows the five access modifier keywords that you can use to specify the accessibility of classes and class members. However, you can only use public and internal (in Visual C#) or Public and Friend (in Visual Basic) to specify the accessibility of the class itself. Access level Visual C# access modifier Accessible by any code in the application public Public Accessible by code in the containing class private Private Accessible by code in the current assembly internal Friend Accessible by code in the containing class and in derived classes Accessible by code in the current assembly and in derived classes protected protected internal Visual Basic access modifier Protected Protected Friend

6-14 Module 6: Fundamentals of Object-Oriented Programming Default Access Levels If you do not specify an access modifier in a class definition, the default access level for the class is as follows: Visual C#. Classes are internal by default. Visual Basic. Classes are Friend by default. If you do not specify an access modifier for a member within a class definition, the default access level for the member is as follows: Visual C#. All members are private by default. Visual Basic. Fields are Private by default and other members are Public by default.

Module 6: Fundamentals of Object-Oriented Programming 6-15 How to Add Fields and Methods to a Class Classes contain fields and methods that define the data and behavior of the class. You can define any number of fields and methods in a class, depending on the purpose and intended functionality of the class. Defining Fields Each field has a name, a data type, and an access modifier. You can place field definitions anywhere within a class. Some programmers prefer to place their field definitions near the start of the class to make the code easy to read for fellow programmers. Another popular convention among many programmers is to prefix the field name with an underscore to distinguish between fields and local variables. Defining Methods A method is a procedure or function in a class. Each method has a name, a parameter list, a return type, and an access modifier. If you do not explicitly specify an access modifier for a method, the default access level is private (in Visual C#) or public (in Visual Basic). You can return a value from a method by using the return (in Visual C#) or Return (in Visual Basic) keyword. If the method does not require any parameters, you can specify an empty parameter list. If the method does not return a value, you can specify a return type of void (in Visual C#) or define the method as a Sub (in Visual Basic). A method has complete and unrestricted access to all the other members in the class. This is an important aspect of object-oriented programming; methods encapsulate operations upon the fields in the class.

6-16 Module 6: Fundamentals of Object-Oriented Programming Example The following example shows a BankAccount class that contains various fields and methods. The class has two fields that represent the name of the account holder and the current balance of the bank account. The class has methods to deposit money into the account, withdraw money from the account, and calculate and return the interest due on the account. The interest calculation assumes a fixed interest rate of 3% for simplicity. public class BankAccount private string _name; private decimal _balance; public void Deposit(decimal amount) _balance += amount; public void Withdraw(decimal amount) _balance -= amount; public decimal CalculateInterest() return _balance * 0.03m; Public Class BankAccount Private _name As String Private _balance As Decimal Public Sub Deposit(ByVal amount As Decimal) _balance += amount End Sub Public Sub Withdraw(ByVal amount As Decimal) _balance -= amount End Sub Public Function CalculateInterest() As Decimal Return _balance * 0.03D End Function End Class

Module 6: Fundamentals of Object-Oriented Programming 6-17 How to Add Properties to a Class One of the most important principles of object-oriented programming is that a class should encapsulate its internal state and implementation. One of the ways you can achieve encapsulation is to ensure that you always define fields as private. However, in some circumstances client code might require access to the field values in a class. The solution to this problem is to define properties that provide controlled access to the field values. Defining Properties A property is a named block of code that can contain a get accessor and a set accessor, as follows: The get accessor must return a value of the specified data type. The set accessor receives an implicit value parameter (in Visual C#) or an explicit value parameter (in Visual Basic), indicating the new value for the property as passed in by the client code. Each property has a name, a return type, and an access modifier. If you do not explicitly specify an access modifier for a property, the default access level is private (in Visual C#) or public (in Visual Basic). The general syntax for properties is as follows. access-modifier return-type property-name get code to return a value set code to use the implicit value parameter to set a value

6-18 Module 6: Fundamentals of Object-Oriented Programming access-modifier Property property-name() As return-type Get code to return a value End Get Set(ByVal value As return-type) code to use the explicit value parameter to set a value End Set End Property Note: If you define a read-only or write-only property in Visual Basic, you must include the ReadOnly or WriteOnly keyword before the Property keyword. There are no equivalent keywords in Visual C#. Example The following example shows how to define three properties in the BankAccount class. All of the properties are public and encapsulate access to private fields in the class. The Name property gets and sets the account holder name. The Balance property is a read-only property that gets the current account balance. The MaximumAllowableWithdrawal property is a write-only property that sets the maximum allowable withdrawal for this bank account. This property is write-only because client code needs to be able to set the property but does not need to query the value. public class BankAccount private string _name; private decimal _balance; private decimal _maximumallowablewithdrawal; public string Name get return _name; set _name = value; public decimal Balance get return _balance; public decimal MaximumAllowableWithdrawal set _maximumallowablewithdrawal = value; // Plus other members.

Module 6: Fundamentals of Object-Oriented Programming 6-19 Public Class BankAccount Private _name As String Private _balance As Decimal Private _maximumallowablewithdrawal As Decimal Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Public ReadOnly Property Balance() As Decimal Get Return _balance End Get End Property Public WriteOnly Property MaximumAllowableWithdrawal() As Decimal Set(ByVal value As Decimal) _maximumallowablewithdrawal = value End Set End Property End Class

6-20 Module 6: Fundamentals of Object-Oriented Programming How to Add Constructors to a Class When you create an object in client code, you must ensure that you also fully initialize it. The easiest way to guarantee that objects are initialized is to define one or more constructors in the class. When you create an object, the common language runtime (CLR) automatically invokes a constructor to initialize the object. Defining Constructors A constructor is a method that the CLR invokes implicitly and automatically when you create an object. The following rules and guidelines apply when you define a constructor: In Visual C#, constructors have the same name as the class in which they are defined. In Visual Basic, constructors are subroutines named New. Constructors must not specify a return value, but they can take parameters. You can define any number of constructors in a class, provided each constructor has a unique parameter list. A constructor that takes no parameters is known as a default constructor. Constructors are typically declared with public accessibility to enable any part of the application to create and initialize objects. If you want to limit the parts of the application that can create and initialize objects, you can define a more restrictive access level for the constructors. Constructors typically initialize some or all of the fields in the object. They can also perform additional initialization tasks such as writing information to a log file. The general syntax for constructors is as follows. access-modifier class-name(parameter-list)

Module 6: Fundamentals of Object-Oriented Programming 6-21 initialization code access-modifier Sub New(parameter-list) initialization code End Sub Example The following example shows how to define three constructors in the BankAccount class: The first constructor is a default constructor that sets the account holder name and initial balance to meaningful default values. The second constructor takes a string parameter. It initializes the account holder name with this parameter and sets the initial balance to zero. The third constructor takes two parameters. It initializes both the account holder name and the initial balance with these parameters. public class BankAccount private string _name; private decimal _balance; public BankAccount() _name = "[Unknown]"; _balance = 0; public BankAccount(string name) _name = name; _balance = 0; public BankAccount(string name, decimal balance) _name = name; _balance = balance; // Plus other members. Public Class BankAccount Private _name As String Private _balance As Decimal

6-22 Module 6: Fundamentals of Object-Oriented Programming Public Sub New() _name = "[Unknown]" _balance = 0 End Sub Public Sub New(ByVal name As String) _name = name _balance = 0 End Sub Public Sub New(ByVal name As String, ByVal balance As Decimal) _name = name _balance = balance End Sub ' Plus other members. End Class To reduce the amount of duplication in overloaded constructors, implement the majority of the initialization tasks in one constructor and then invoke that constructor from the other constructors. The following example shows how to rewrite the first two BankAccount constructors so that they invoke the third BankAccount constructor. public BankAccount() : this("[unknown]", 0) public BankAccount(string name) : this(name, 0) public BankAccount(string name, decimal balance) _name = name; _balance = balance; Public Sub New() Me.New("[Unknown]", 0) End Sub Public Sub New(ByVal name As String) Me.New(name, 0) End Sub

Module 6: Fundamentals of Object-Oriented Programming 6-23 Public Sub New(ByVal name As String, ByVal balance As Decimal) _name = name _balance = balance End Sub

6-24 Module 6: Fundamentals of Object-Oriented Programming How to Use Namespaces to Organize Classes The.NET Framework enables you to use namespaces to organize your classes. You can use namespaces to group classes into a logical scope to make your code easier to understand. Namespaces also help to avoid accidental name clashes between unrelated classes that have the same name. Defining Namespaces To define a namespace, you use the namespace keyword (in Visual C#) or the Namespace keyword (in Visual Basic). All classes that appear between the start and end of a namespace definition are part of that namespace. Each class belongs to one namespace, and a namespace typically contains several classes. The general syntax for defining namespaces is as follows. namespace namespace-name // Place class definitions here.

Module 6: Fundamentals of Object-Oriented Programming 6-25 Namespace namespace-name ' Place class definitions here. End Namespace Importing Namespaces There are two ways to access a class that you have defined in another namespace, as follows: Refer to the class by its fully qualified name. For example, the fully qualified name of the MessageBox class is System.Windows.Forms.MessageBox. Import the namespace that contains the class and then use the class name without its namespace prefix. To import a namespace, you use the using keyword (in Visual C#) or the Imports keyword (in Visual Basic). The general syntax for importing a namespace is as follows. using namespace-name; Imports namespace-name Example The following example shows how to organize classes into namespaces and how to import namespaces to access classes defined in those namespaces. The example consists of the following three source files: BankAccount.cs or BankAccount.vb. This defines the BankAccount class in the AccountManagement namespace. The source file imports the System namespace so that it can access the DateTime type. It also imports the CustomerManagement namespace so that it can access the Customer type. Customer.cs or Customer.vb. This defines the Customer class in the CustomerManagement namespace. One of the fields in the Customer class is of type CreditRating. The CreditRating class is in the same namespace as the Customer class, so there is no need to import any additional namespaces. CreditRating.cs or CreditRating.vb. This defines the CreditRating class in the CustomerManagement namespace. Notice that the CustomerManagement namespace spans two source files Customer.cs and CreditRating.cs (or Customer.vb and CreditRating.vb). // ----------------------------------------------------------------------------- // BankAccount.cs // -----------------------------------------------------------------------------

6-26 Module 6: Fundamentals of Object-Oriented Programming using System; using CustomerManagement; // For the DateTime type. // For the Customer type. // Import other namespaces here if needed. namespace AccountManagement public class BankAccount private Customer _accountholder; private DateTime _accountcreationtime; // Plus other members. // ----------------------------------------------------------------------------- // Customer.cs // ----------------------------------------------------------------------------- // Import namespaces here, as needed. namespace CustomerManagement public class Customer private string _name; private CreditRating _creditrating; // Plus other members. // ----------------------------------------------------------------------------- // CreditRating.cs // ----------------------------------------------------------------------------- // Import namespaces here, as needed. namespace CustomerManagement public class CreditRating // Members. ' ------------------------------------------------------------------------------ ' BankAccount.vb ' ------------------------------------------------------------------------------ Imports System Imports CustomerManagement ' For the DateTime type. ' For the Customer type. ' Import other namespaces here, as needed.

Module 6: Fundamentals of Object-Oriented Programming 6-27 Namespace AccountManagement Public Class BankAccount Private _accountholder As Customer Private _accountcreationtime As DateTime ' Plus other members. End Class End Namespace ' ------------------------------------------------------------------------------ ' Customer.vb ' ------------------------------------------------------------------------------ ' Import namespaces here, as needed. Namespace CustomerManagement Public Class Customer Private _name As String Private _creditrating As CreditRating ' Plus other members. End Class End Namespace ' ------------------------------------------------------------------------------ ' CreditRating.vb ' ------------------------------------------------------------------------------ ' Import namespaces here if needed. Namespace CustomerManagement Public Class CreditRating ' Members. End Class End Namespace

6-28 Module 6: Fundamentals of Object-Oriented Programming Lesson 3: Creating a Class Instance This lesson describes how to create an instance of a class and how to access members of the instance. The lesson also describes how the CLR manages the lifetime of objects. Additionally, the lesson introduces the concept of structures. Structures are similar to classes. However, they are allocated in a different way by the CLR. The lesson describes the need for structures in the.net Framework. It also shows you how to define and use structures in Visual C# and Visual Basic. Objectives After completing this lesson, you will be able to: Create and use an instance of a class. Describe how objects are allocated and deallocated. Describe what a structure is. Declare and use structures.

Module 6: Fundamentals of Object-Oriented Programming 6-29 How to Create and Use an Instance of a Class When you have defined a class, you can create instances and invoke properties, methods, and any other accessible members of the instances. Creating an Instance of a Class To create an instance of a class, you use the new operator (in Visual C#) or the New operator (in Visual Basic). After this operator, you specify the class type that you want to create an instance of, followed by any parameters that you want to pass to the constructor. The constructor implicitly returns the new instance of the class, which you typically assign to a variable so that you can access the instance later. The following code shows the general syntax for creating an instance of a class. class-name variable-name = new class-name(constructor-parameter-values); Dim variable-name As New class-name(constructor-parameter-values) Using an Instance of a Class To access a member of an instance, use the name of the instance, followed by a period, followed by the name of the member. The following rules and guidelines apply when you access a member of an instance: To access a method, use parentheses after the name of the method. Within the parentheses, pass the values for any parameters that the method requires.

6-30 Module 6: Fundamentals of Object-Oriented Programming Note: If the method does not take any parameters, the parentheses are still required in Visual C# but not in Visual Basic. To access a property, use the property name as if it were a public data item in the class. The compiler implicitly invokes the get accessor or the set accessor of the instance, depending on whether you get or set the property value. Example The following example shows how to create and use an instance of the BankAccount class. The example performs the following tasks: Creates a BankAccount instance and initializes it by using the BankAccount constructor that takes parameters representing the name of the account holder and the initial balance. Invokes the Deposit method on the BankAccount instance to deposit $5 into the account. Uses the Name property to set the name of the account holder to Samantha. Uses the Name property to get the name of the account holder and then display the name and balance. BankAccount account = new BankAccount("Sam", 100); account.deposit(5); account.name = "Samantha"; Console.WriteLine("0 1", account.name, account.balance); Dim account As New BankAccount("Sam", 100) account.deposit(5) account.name = "Samantha" Console.WriteLine("0 1", account.name, account.balance)

Module 6: Fundamentals of Object-Oriented Programming 6-31 How Objects Are Allocated and Deallocated All objects consume system resources such as memory, file handles, and database connections. The CLR manages resources automatically, and usually you do not need to release objects explicitly when you have finished using them. However, you will design more efficient applications if you understand how resource management works. Object Allocation When you create an instance of a class, the CLR allocates memory for the object on the managed heap. The managed heap is the area of memory that the CLR uses for allocating objects. Your application receives a reference to the object on the managed heap. You retain the reference for as long as you need the object. Object Deallocation When you have finished using an object, you can set your object reference to null (in Visual C#) or Nothing (in Visual Basic) to indicate that you no longer need a reference to the object. When there are no remaining references to the object, the object becomes available for garbage collection. The CLR uses garbage collection to manage allocated resources. The garbage collector reclaims the memory for an object when that object can no longer be reached by any running code in your application. The garbage collection algorithm is nondeterministic; you cannot determine when the garbage collector will run next. You can define a destructor in a class to perform de-initialization tasks. The CLR invokes the destructor on an object just before the object is garbage collected. However, because the garbage collection algorithm is nondeterministic, you cannot predict how long it will

6-32 Module 6: Fundamentals of Object-Oriented Programming be before the destructor is invoked on the object. The destructor might be called immediately. Alternatively, it might be called several hours later. Tip: To achieve deterministic object disposal, implement the IDisposable interface and provide a Dispose method in your class. For more information, see "IDisposable interface" in Visual Studio Help.

Module 6: Fundamentals of Object-Oriented Programming 6-33 What Are Structures? Most programming languages provide built-in data types, such as integers and floatingpoint numbers. These types are copied when they are passed as arguments into a method; that is, the method receives a copy of the value rather than a reference to the original value. In the.net Framework, these data types are known as value types or structures. The runtime supports two types of structures: Built-in structures User-defined structures Built-in Structures The.NET Framework defines built-in structures that correspond and are identical to the primitive data types that programming languages use. The following table lists some of the built-in structures in the.net Framework. It also shows the equivalent Visual C# and Visual Basic keywords. Structure type Equivalent Visual C# keyword Equivalent Visual Basic keyword System.Byte byte Byte System.Int16 short Short System.Int32 int Integer System.Int64 long Long System.Single float Single System.Double double Double System.Decimal decimal Decimal

6-34 Module 6: Fundamentals of Object-Oriented Programming Structure type Equivalent Visual C# keyword Equivalent Visual Basic keyword System.Boolean bool Boolean System.Char char Char User-Defined Structures Visual C# and Visual Basic enable you to define your own structures. Structures are similar to classes. For example, structures can contain fields, properties, methods, and constructors. However, there are some important differences between structures and classes. The following table describes these differences. Behavior Classes Structures Allocation Deallocation Passing into methods Objects are allocated on the managed heap. Objects are deallocated when your application no longer has any references to them. The garbage collector reclaims the memory for deallocated objects when it runs. By default, a method receives a reference that refers to the original object. Objects are allocated on an area of memory called the stack. Objects are deallocated when they go out of scope. For example, if you create an object inside a method, the object is deallocated when the method returns. By default, a method receives a copy of the original object. Any changes that the method makes to the object will be discarded when the method returns. Classes vs. Structures When you define a new type in your application, you must decide whether to define the type as a class or as a structure. The main data types in an application are typically defined as classes. For example, a banking system might have classes such as BankAccount, Customer, and OverdraftFacility. The numerical data types in an application are typically defined as structures. For example, a banking system might have structures such as Currency, AccountIdentifier, and MoneyTransfer.

Module 6: Fundamentals of Object-Oriented Programming 6-35 How to Declare and Use Structures To use a structure in an application, you must first declare the structure type. You can declare structure types in any source file in your application. When you have declared a structure type, you can create and use structure objects in the rest of your application. Declaring a Structure Type The syntax for declaring a structure is similar to the syntax for declaring a class, except that you use the struct keyword rather than class (in Visual C#) or the Structure keyword rather than Class (in Visual Basic). Structures can contain fields, properties, methods, and parameterized constructors. However, they cannot contain no-parameter constructors. Creating and Using Structure Objects The syntax you require to use structures is the same as the syntax to use a class. To create a structure object, use the new operator (in Visual C#) or the New operator (in Visual Basic). To access members of a structure object, use the object name, followed by a period, followed by the name of the member. Example The following example shows how to create a structure type named UsCurrency, which represents a currency value in U.S. dollars. The structure has a field named _centsamount that stores the currency value in cents. The structure provides two constructors that offer alternative ways to initialize UsCurrency objects. The structure has a read-only property named Amount that returns a string representation of a UsCurrency object, formatted to two decimal places.

6-36 Module 6: Fundamentals of Object-Oriented Programming The example also shows how to create and use UsCurrency objects in application code. The example creates two UsCurrency objects, assigns them to local variables named mine and yours, and then uses the Amount property to display their values. public struct UsCurrency private long _centsamount; public UsCurrency(int dollars, int cents) _centsamount = (dollars * 100) + cents; public UsCurrency(decimal dollarsandcents) _centsamount = (long)(dollarsandcents * 100); public string Amount get return string.format("$0:n2", _centsamount / 100.0); // Create and use UsCurrency objects in the application. UsCurrency mine = new UsCurrency(10, 50); UsCurrency yours = new UsCurrency(99.99m); Console.WriteLine("I have 0, you have 1", mine.amount, yours.amount); Public Structure UsCurrency Private _centsamount As Long Public Sub New(ByVal dollars As Integer, ByVal cents As Integer) _centsamount = (dollars * 100) + cents End Sub Public Sub New(ByVal dollarsandcents As Decimal) _centsamount = CLng(dollarsAndCents * 100) End Sub Public ReadOnly Property Amount() As String Get Return String.Format("$0:n2", _centsamount / 100.0) End Get End Property End Structure ' Create and use UsCurrency objects in the application. Dim mine As New UsCurrency(10, 50)

Module 6: Fundamentals of Object-Oriented Programming 6-37 Dim yours As New UsCurrency(99.99D) Console.WriteLine("I have 0, you have 1", mine.amount, yours.amount)

6-38 Module 6: Fundamentals of Object-Oriented Programming Lab: Fundamentals of Object-Oriented Programming After completing this lab, you will be able to: Create a class. Create and use an instance of the class. Estimated time to complete this lab: 50 minutes Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must: Start the 4994A-LON-DEV-06 virtual machine. Log on to the virtual machine with the user name Student and the password Pa$$w0rd. Lab Scenario Your team leader at Adventure Works has asked you to enhance the Sales application so that users can view and modify sales details for individual sales people. You will define a SalesPerson class that encapsulates data and behavior for a sales person. You will then use the SalesPerson class in the code-behind files for the forms in the Sales application.

Module 6: Fundamentals of Object-Oriented Programming 6-39 Exercise 1: Creating a SalesPerson Class In this exercise, you will create a SalesPerson class in the Sales application. You will add fields, properties, and methods to the class. These members represent the data and behavior for individual sales people. You will also add a constructor to the class to initialize SalesPerson objects. The principal tasks for this exercise are as follows: Add a public SalesPerson class to the Sales application. Add fields and a constructor to the class. Add properties and methods to the class. Add a public SalesPerson class to the Sales application 1. Start Microsoft Visual Studio 2005. 2. On the File menu, point to Open, and then click Project/Solution. 3. In the Open Project dialog box, open the SalesApplication.sln solution file for the starter Sales application. If you are using Visual C#, the solution file is located in the E:\Labfiles\Starter\CS\SalesApplication folder. If you are using Visual Basic, the solution file is located in the E:\Labfiles\Starter\VB\SalesApplication folder. 4. Add a new class named SalesPerson to the project as follows: a. In Solution Explorer, right-click the SalesApplication project, point to Add, and then click Class. b. In the Add New Item SalesApplication dialog box, type SalesPerson in the text box, and then click Add. 5. If you use Visual C#, modify the generated SalesPerson class definition to make the class public. Note: If you use Visual Basic, the generated class definition is already Public. Your class definition should resemble the following. public class SalesPerson Public Class SalesPerson

6-40 Module 6: Fundamentals of Object-Oriented Programming End Class Add fields and a constructor to the class 1. Add the following three private fields to the SalesPerson class. Name of field Visual C# data type Visual Basic data type _name string String _totalsales decimal Decimal _numberofsales int Integer Your code should resemble the following. private string _name; private decimal _totalsales; private int _numberofsales; Private _name As String Private _totalsales As Decimal Private _numberofsales As Integer 2. Add a public constructor to the SalesPerson class. The constructor requires a string parameter for the name of the sales person. Implement the constructor as follows: a. Use the string parameter to initialize the _name field. b. Initialize the _totalsales field to 0. c. Initialize the _numberofsales field to 0. Your code should resemble the following. public SalesPerson(string name) _name = name; _totalsales = 0; _numberofsales = 0; Public Sub New(ByVal name As String) _name = name _totalsales = 0 _numberofsales = 0 End Sub 3. On the Build menu, click Build Solution. Verify that the solution builds without any errors.

Module 6: Fundamentals of Object-Oriented Programming 6-41 Add properties and methods to the class 1. Add a public string property named Name to the SalesPerson class, to get and set the name of the sales person. Your code should resemble the following. public string Name get return _name; set _name = value; Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property 2. Add a public read-only decimal property named TotalSales to the SalesPerson class, to get the total sales for the sales person. Your code should resemble the following. public decimal TotalSales get return _totalsales; Public ReadOnly Property TotalSales() As Decimal Get Return _totalsales End Get End Property 3. Add a public read-only decimal property named AverageSale to the SalesPerson class, to return the average sale for the sales person. Implement the property as follows: If the number of sales for the sales person is zero, return 0. Otherwise, return the total sales divided by the number of sales. Your code should resemble the following.

6-42 Module 6: Fundamentals of Object-Oriented Programming public decimal AverageSale get if (_numberofsales == 0) return 0; else return _totalsales / _numberofsales; Public ReadOnly Property AverageSale() As Decimal Get If _numberofsales = 0 Then Return 0 Else Return _totalsales / _numberofsales End If End Get End Property 4. Add a public method named AddSale to the SalesPerson class. The method requires a decimal parameter for the value of the new sale. Implement the method as follows: a. Add the value of the new sale to the total sales for the sales person. b. Increment the number of sales for the sales person. Your code should resemble the following. public void AddSale(decimal sale) _totalsales += sale; _numberofsales++; Public Sub AddSale(ByVal sale As Decimal) _totalsales += sale _numberofsales += 1 End Sub 5. On the Build menu, click Build Solution. Verify that the solution builds without any errors.

Module 6: Fundamentals of Object-Oriented Programming 6-43 Exercise 2: Creating and Using a SalesPerson Object In this exercise, you will add code to the Sales application to create a SalesPerson object and invoke properties and methods on the SalesPerson object. The principal tasks for this exercise are as follows: Create and use a SalesPerson instance. Build and test the application. Note: The starter code contains TODO comments that indicate where you must add or modify code. To view the TODO comments in Visual Studio, on the View menu, click Task List. Then, in the Task List window, in the list, select Comments. Create and use a SalesPerson instance 1. In Solution Explorer, right-click the SalesForm form, and then click View Code. 2. Locate the TODO: Declare a SalesPerson field named _salesperson comment at the start of the SalesForm class. Add code to declare a private SalesPerson field named _salesperson. Your code should resemble the following. private SalesPerson _salesperson; Private _salesperson As SalesPerson 3. Locate the TODO: Create a SalesPerson object and assign it to _salesperson comment in the constructor. Add code to create a SalesPerson object with the specified name, and assign the object to the _salesperson field. The _salesperson field now refers to a SalesPerson object. The SalesPerson object represents the sales person data and behavior that the form will use. Your code should resemble the following. _salesperson = new SalesPerson(name); _salesperson = New SalesPerson(name) 4. Locate the TODO: Display the details for the sales person comment in the DisplaySalesPersonDetails method. Modify the method so that it displays the name, total sales, and average sale for the sales person. Your code should resemble the following.

6-44 Module 6: Fundamentals of Object-Oriented Programming namelabel.text = string.format("name: 0", _salesperson.name); totalsaleslabel.text = string.format("total sales: 0:c2", _salesperson.totalsales); averagesalelabel.text = string.format("average sale: 0:c2", _salesperson.averagesale); namelabel.text = String.Format("Name: 0", _salesperson.name) totalsaleslabel.text = String.Format("Total sales: 0:c2", salesperson.totalsales) averagesalelabel.text = String.Format("Average sale: 0:c2", salesperson.averagesale) 5. Locate the TODO: Add the sale to the sales person comment in the addsalebutton_click method. Add code to invoke the AddSale method on the _salesperson object, passing the value of the sale as a parameter into the AddSale method. Your code should resemble the following. _salesperson.addsale(sale); _salesperson.addsale(sale) Build and test the application 1. On the Build menu, click Build Solution. Verify that the solution builds without any errors. 2. On the Debug menu, click Start Debugging. 3. In the Main Form form, in the Enter sales person name box, enter your name, and then click the Sales button. Verify that the Sales form displays your name and the value zero for the total sales and average sale. 4. In the Sales form, in the Sale box, enter a number such as 100000, and then click Add Sale. Verify that the Sales form displays the updated value for the total sales and average sale. 5. Repeat the previous step.

Module 6: Fundamentals of Object-Oriented Programming 6-45 Verify that the Sales form displays the correct value for the total sales and average sale each time. 6. Close the Sales form and then close the Main Form form. Results Checklist The following is a checklist of results for you to verify that you have performed this lab successfully. Ensure that you: Added a SalesPerson class to the Sales application. Defined fields in the SalesPerson class. Defined a constructor in the SalesPerson class. Defined properties and methods in the SalesPerson class. Added code to the Sales application to create and use a SalesPerson object. Lab Shutdown After you complete the lab, you must shut down the 4994A-LON-DEV-06 virtual machine and discard any changes. Important: If the Close dialog box appears, ensure that Turn off and delete changes is selected and then click OK.

6-46 Module 6: Fundamentals of Object-Oriented Programming Lab Discussion Discuss the following questions: How do you choose whether to implement functionality as a method or a property? Why is it important to declare fields as private? How many constructors should you define in a class? How do you create an instance of a class? How do you access methods and properties on an instance?