Module 6: Fundamentals of Object- Oriented Programming

Size: px
Start display at page:

Download "Module 6: Fundamentals of Object- Oriented Programming"

Transcription

1 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

2 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, addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, 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 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

3 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.

4 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.

5 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 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.

7 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.

8 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

9 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.

10 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.

11 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)

12 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.

13 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

14 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.

15 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

16 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.

17 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.

18 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

19 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

20 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.

21 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

22 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)

23 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

24 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

25 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

26 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.

27 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 //

28 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.

29 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

30 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.

31 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.

32 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)

33 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

34 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.

35 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

36 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.

37 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.

38 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)

39 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)

40 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.

41 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 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

42 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.

43 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.

44 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.

45 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.

46 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 , 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.

47 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.

48 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?

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

Lab Answer Key for Module 1: Creating Databases and Database Files Lab Answer Key for Module 1: Creating Databases and Database Files Table of Contents Lab 1: Creating Databases and Database Files 1 Exercise 1: Creating a Database 1 Exercise 2: Creating Schemas 4 Exercise

More information

Lab Answer Key for Module 8: Implementing Stored Procedures

Lab Answer Key for Module 8: Implementing Stored Procedures Lab Answer Key for Module 8: Implementing Stored Procedures Table of Contents Lab 8: Implementing Stored Procedures 1 Exercise 1: Creating Stored Procedures 1 Exercise 2: Working with Execution Plans 6

More information

Introduction To C#.NET

Introduction To C#.NET Introduction To C#.NET Microsoft.Net was formerly known as Next Generation Windows Services(NGWS).It is a completely new platform for developing the next generation of windows/web applications. However

More information

Module 4: Data Types and Variables

Module 4: Data Types and Variables Module 4: Data Types and Variables Table of Contents Module Overview 4-1 Lesson 1: Introduction to Data Types 4-2 Lesson 2: Defining and Using Variables 4-10 Lab:Variables and Constants 4-26 Lesson 3:

More information

Advanced Programming Using Visual Basic 2008

Advanced Programming Using Visual Basic 2008 Building Multitier Programs with Classes Advanced Programming Using Visual Basic 2008 The OOP Development Approach OOP = Object Oriented Programming Large production projects are created by teams Each

More information

Module 9: Validating User Input

Module 9: Validating User Input Module 9: Validating User Input Table of Contents Module Overview 9-1 Lesson 1: Restricting User Input 9-2 Lesson 2: Implementing Field-Level Validation 9-8 Lesson 3: Implementing Form-Level Validation

More information

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

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO 2010 Course: 10550A; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN This course teaches you

More information

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

Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET Software Development Unit 4 Objects in Visual Basic.NET Aims This unit proceeds to the heart of object-oriented programming, introducing the mechanisms for creating new classes of object, defining their

More information

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

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int, Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class

More information

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Module 3: Managing Groups

Module 3: Managing Groups Module 3: Managing Groups Contents Overview 1 Lesson: Creating Groups 2 Lesson: Managing Group Membership 20 Lesson: Strategies for Using Groups 27 Lesson: Using Default Groups 44 Lab: Creating and Managing

More information

Programming in Visual Basic with Microsoft Visual Studio 2010

Programming in Visual Basic with Microsoft Visual Studio 2010 Programming in Visual Basic with Microsoft Visual Studio 2010 Course 10550; 5 Days, Instructor-led Course Description This course teaches you Visual Basic language syntax, program structure, and implementation

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Microsoft Exchange Server SMTPDiag

Microsoft Exchange Server SMTPDiag Microsoft Exchange Server SMTPDiag Contents Microsoft Exchange Server SMTPDiag...1 Contents... 2 Microsoft Exchange Server SMTPDiag...3 SMTPDiag Arguments...3 SMTPDiag Results...4 SMTPDiag Tests...5 Copyright...5

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

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

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 2 Building Multitier Programs with Classes McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Objectives Discuss object-oriented terminology Create your own class and instantiate

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

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

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Module 2: Introduction to a Managed Execution Environment

Module 2: Introduction to a Managed Execution Environment Module 2: Introduction to a Managed Execution Environment Contents Overview 1 Writing a.net Application 2 Compiling and Running a.net Application 11 Lab 2: Building a Simple.NET Application 29 Review 32

More information

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

More C++ : Vectors, Classes, Inheritance, Templates Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4 : Classes & Objects Lecture Contents What is a class? Class definition: Data Methods Constructors Properties (set/get) objects

More information

10. Abstract Data Types

10. Abstract Data Types 10. Abstract Data Types 11.1 The Concept of Abstraction The concept of abstraction is fundamental in programming Nearly all programming languages support process abstraction with subprograms Nearly all

More information

Implementing Subprograms

Implementing Subprograms Implementing Subprograms 1 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms Blocks Implementing

More information

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

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

Building Multitier Programs with Classes

Building Multitier Programs with Classes 2-1 2-1 Building Multitier Programs with Classes Chapter 2 This chapter reviews object-oriented programming concepts and techniques for breaking programs into multiple tiers with multiple classes. Objectives

More information

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Object-Oriented Programming in C# (VS 2015)

Object-Oriented Programming in C# (VS 2015) Object-Oriented Programming in C# (VS 2015) This thorough and comprehensive 5-day course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes

More information

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

9/21/2010. Based on Chapter 2 in Advanced Programming Using Visual Basic.NET by Bradley and Millspaugh Building Multitier Programs with Classes Based on Chapter 2 in Advanced Programming Using Visual Basic.NET by Bradley and Millspaugh The Object-Oriented Oriented (OOP) Development Approach Large production

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4 (a): Classes & Objects Lecture Contents 2 What is a class? Class definition: Data Methods Constructors objects Static members

More information

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

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

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4 : Classes & Objects Lecture Contents What is a class? Class definition: Data Methods Constructors Properties (set/get) objects

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Abstract Data Types and Encapsulation Concepts ISBN 0-321-33025-0 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4 : Classes & Objects Lecture Contents What is a class? Class definition: Data Methods Constructors Properties (set/get) objects

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

Abstract Data Types and Encapsulation Concepts

Abstract Data Types and Encapsulation Concepts Abstract Data Types and Encapsulation Concepts The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes The concept of abstraction

More information

Module 7: Automating Administrative Tasks

Module 7: Automating Administrative Tasks Module 7: Automating Administrative Tasks Table of Contents Module Overview 7-1 Lesson 1: Automating Administrative Tasks in SQL Server 2005 7-2 Lesson 2: Configuring SQL Server Agent 7-10 Lesson 3: Creating

More information

Module 3: Creating Objects in C#

Module 3: Creating Objects in C# Module 3: Creating Objects in C# Contents Overview 1 Lesson: Defining a Class 2 Lesson: Declaring Methods 18 Lesson: Using Constructors 35 Lesson: Using Static Class Members 44 Review 52 Lab 3.1: Creating

More information

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

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language

More information

Object-Oriented Programming in C# (VS 2012)

Object-Oriented Programming in C# (VS 2012) Object-Oriented Programming in C# (VS 2012) This thorough and comprehensive course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes the C#

More information

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

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations , 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials

More information

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

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net? Introduction to.net, C#, and Visual Studio C# Programming Part I Administrivia January 8 Administrivia Course Structure When: Wednesdays 10 11am (and a few Mondays as needed) Where: Moore 100B This lab

More information

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

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES Introduction In this preliminary chapter, we introduce a couple of topics we ll be using throughout the book. First, we discuss how to use classes and object-oriented programming (OOP) to aid in the development

More information

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

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

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.

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. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

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

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 1. Which language is not a true object-oriented programming language? A. VB 6 B. VB.NET C. JAVA D. C++ 2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a)

More information

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

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

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

And Even More and More C++ Fundamentals of Computer Science And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

CMSC 4023 Chapter 11

CMSC 4023 Chapter 11 11. Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 03: Creating Classes MOUNA KACEM mouna@cs.wisc.edu Spring 2019 Creating Classes 2 Constructors and Object Initialization Static versus non-static fields/methods Encapsulation

More information

Module 3-1: Building with DIRS and SOURCES

Module 3-1: Building with DIRS and SOURCES Module 3-1: Building with DIRS and SOURCES Contents Overview 1 Lab 3-1: Building with DIRS and SOURCES 9 Review 10 Information in this document, including URL and other Internet Web site references, is

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 03: Creating Classes MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Constructors and Object Initialization Static versus non-static fields/methods Encapsulation

More information

Module 8: Implementing Stored Procedures

Module 8: Implementing Stored Procedures Module 8: Implementing Stored Procedures Table of Contents Module Overview 8-1 Lesson 1: Implementing Stored Procedures 8-2 Lesson 2: Creating Parameterized Stored Procedures 8-10 Lesson 3: Working With

More information

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

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

Hands-On Lab. Lab Manual HOL007 Understanding, Designing, and Refactoring Code Using the New Class Designer Tool in Microsoft Visual Studio 2005 Hands-On Lab Lab Manual HOL007 Understanding, Designing, and Refactoring Code Using the New Class Designer Tool in Microsoft Visual Studio 2005 Please do not remove this manual from the lab Page 1 Information

More information

CHECK PROCESSING. A Select Product of Cougar Mountain Software

CHECK PROCESSING. A Select Product of Cougar Mountain Software CHECK PROCESSING A Select Product of Cougar Mountain Software Check Processing Copyright Notification At Cougar Mountain Software, Inc., we strive to produce high-quality software at reasonable prices.

More information

Introduction to Managed Code

Introduction to Managed Code McGrath.book Page 89 Thursday, December 7, 2006 10:04 AM 3 Introduction to Managed Code Technology is dominated by two types of people: those who understand what they do not manage, and those who manage

More information

C11: Garbage Collection and Constructors

C11: Garbage Collection and Constructors CISC 3120 C11: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/5/2017 CUNY Brooklyn College 1 Outline Recap Project progress and lessons

More information

Exclaimer Signature Manager 2.0 Release Notes

Exclaimer Signature Manager 2.0 Release Notes Exclaimer Release Notes Exclaimer UK +44 (0) 1252 531 422 USA 1-888-450-9631 info@exclaimer.com 1 Contents About these Release Notes... 3 Release Number... 3 Hardware... 3 Software... 3 Hardware... 3 Software...

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

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

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

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

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. Chapter 12 OOP: Creating Object- Oriented Programs McGraw-Hill Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. Objectives (1 of 2) Use object-oriented terminology correctly. Create

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts

Chapter 11. Abstract Data Types and Encapsulation Concepts Chapter 11 Abstract Data Types and Encapsulation Concepts The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes The concept

More information

Imperative Languages!

Imperative Languages! Imperative Languages! Java is an imperative object-oriented language. What is the difference in the organisation of a program in a procedural and an objectoriented language? 30 class BankAccount { private

More information

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

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

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

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

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑   ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构 孟小亮 Xiaoliang MENG, 答疑 EMAIL: 1920525866@QQ.COM ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data

More information

Microsoft Dynamics GP. Extender User s Guide

Microsoft Dynamics GP. Extender User s Guide Microsoft Dynamics GP Extender User s Guide Copyright Copyright 2009 Microsoft Corporation. All rights reserved. Complying with all applicable copyright laws is the responsibility of the user. Without

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

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

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Microsoft Exchange 2000 Server Mailbox Folder Structure. Technical Paper

Microsoft Exchange 2000 Server Mailbox Folder Structure. Technical Paper Microsoft Exchange 2000 Server Mailbox Folder Structure Technical Paper Published: April 2002 Table of Contents Introduction...3 Mailbox Creation in Exchange 2000...3 Folder Structure in an Exchange 2000

More information

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

Microsoft Dynamics GP Release Integration Guide For Microsoft Retail Management System Headquarters Microsoft Dynamics GP Release 10.0 Integration Guide For Microsoft Retail Management System Headquarters Copyright Copyright 2007 Microsoft Corporation. All rights reserved. Complying with all applicable

More information

CPS122 Lecture: Defining a Class

CPS122 Lecture: Defining a Class Objectives: CPS122 Lecture: Defining a Class last revised January 14, 2016 1. To introduce structure of a Java class 2. To introduce the different kinds of Java variables (instance, class, parameter, local)

More information

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

2559 : Introduction to Visual Basic.NET Programming with Microsoft.NET 2559 : Introduction to Visual Basic.NET Programming with Microsoft.NET Introduction Elements of this syllabus are subject to change. This five-day instructor-led course provides students with the knowledge

More information

EECS168 Exam 3 Review

EECS168 Exam 3 Review EECS168 Exam 3 Review Exam 3 Time: 2pm-2:50pm Monday Nov 5 Closed book, closed notes. Calculators or other electronic devices are not permitted or required. If you are unable to attend an exam for any

More information

An Introduction to C++

An Introduction to C++ An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface

More information

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

C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Module 8: Building a Windows Forms User Interface

Module 8: Building a Windows Forms User Interface Module 8: Building a Windows Forms User Interface Table of Contents Module Overview 8-1 Lesson 1: Managing Forms and Dialog Boxes 8-2 Lesson 2: Creating Menus and Toolbars 8-13 Lab: Implementing Menus

More information

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

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

More information

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

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000 Objects and Classes Mark Allen Weiss Copyright 2000 8/30/00 1 Basic OO Principles Objects are entities that have structure and state. Each object defines operations that may access or manipulate that state.

More information

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

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211 02 Features of C#, Part 1 Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211 Module Overview Constructing Complex Types Object Interfaces and Inheritance Generics Constructing

More information

Chapter 12: How to Create and Use Classes

Chapter 12: How to Create and Use Classes CIS 260 C# Chapter 12: How to Create and Use Classes 1. An Introduction to Classes 1.1. How classes can be used to structure an application A class is a template to define objects with their properties

More information

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

Deploying Windows Server 2003 Internet Authentication Service (IAS) with Virtual Local Area Networks (VLANs) Deploying Windows Server 2003 Internet Authentication Service (IAS) with Virtual Local Area Networks (VLANs) Microsoft Corporation Published: June 2004 Abstract This white paper describes how to configure

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information