MELJUN CORTES Visual Basic 2005 Object-Oriented Programming

58
Visual Basic 2005 Visual Basic 2005 V. OBJECT-ORIENTED PROGRAMMING MELJUN CORTES MELJUN CORTES

description

MELJUN CORTES Visual Basic 2005 Object-Oriented Programming

Transcript of MELJUN CORTES Visual Basic 2005 Object-Oriented Programming

Page 1: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Visual Basic 2005Visual Basic 2005V. OBJECT-ORIENTED PROGRAMMING

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Introduction to Classes and ObjectsIntroduction to Classes and ObjectsObjectives

OBJECT-ORIENTED PROGRAMMING 2

In this chapter you will learn:•What classes, objects, methods, instance variables and properties are.•How to declare a class and use it to create an object.•How to implement a class's behaviors as methods.•How to implement a class's attributes as instance variables and properties.•How to call an object's methods to make them perform their tasks.•The differences between instance variables of a class and local variables of a method.•How to use a constructor to ensure that an object's attributes are initialized when the object is created.•The differences between value types and reference types.•How to use properties to ensure that only valid data is placed in attributes

Visual Basic 2005

Page 3: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

OverviewOverview

Object orientation uses classes to encapsulate instance variables (data) and methods (behaviors)

Objects have the ability to hide their implementation from other objects

Objects are unaware of how other objects are implemented

OBJECT-ORIENTED PROGRAMMING 3

Visual Basic 2005

Introduction to Classes and Objects

Page 4: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Classes vs ObjectsClasses vs Objects

A class is a type of somethingYou can think of a class as being the

blueprint out of which objects can be constructed

OBJECT-ORIENTED PROGRAMMING 4

Car Blueprint (Class)

Visual Basic 2005

Introduction to Classes and Objects

Page 5: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Classes vs ObjectsClasses vs Objects

An object is an instance of a classFor example, you may have several

instances of a class named CarEach instance of Car is an object and may

be given its own name

OBJECT-ORIENTED PROGRAMMING 5

Actual Cars (Objects)

Visual Basic 2005

Introduction to Classes and Objects

Page 6: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Classes vs ObjectsClasses vs Objects

Class vs. Object

OBJECT-ORIENTED PROGRAMMING 6

Car Blueprint (Class) Actual Cars (Objects)

Visual Basic 2005

Introduction to Classes and Objects

Page 7: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating a ClassCreating a Class

You can add a class from Project menu and selecting the Add Class item or by right-clicking the project from the Solution Explorer and selecting Add then Class

OBJECT-ORIENTED PROGRAMMING 7

Click Add Class menu item to

create a class in your project

Visual Basic 2005

Introduction to Classes and Objects

Page 8: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating a ClassCreating a Class

Class declaration with one method

OBJECT-ORIENTED PROGRAMMING 8

' Class declaration with one method.Public Class GradeBook

' display a welcome message to the GradeBook user Public Sub DisplayMessage() Console.WriteLine("Welcome to the Grade Book!") End Sub ' DisplayMessage

End Class

' Class declaration with one method.Public Class GradeBook

' display a welcome message to the GradeBook user Public Sub DisplayMessage() Console.WriteLine("Welcome to the Grade Book!") End Sub ' DisplayMessage

End Class

Class keyword DisplayMessage is a method of Class

GradeBook

Visual Basic 2005

Introduction to Classes and Objects

Page 9: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating a ClassCreating a Class

Creating an object of class GradeBook

OBJECT-ORIENTED PROGRAMMING 9

Module ModGradeBookTest ' Main begins program execution Sub Main() ' initialize gradeBook to refer to a new GradeBook object Dim gradeBook As New GradeBook()

' call gradeBook's DisplayMessage method gradeBook.DisplayMessage() End Sub ' MainEnd Module

Module ModGradeBookTest ' Main begins program execution Sub Main() ' initialize gradeBook to refer to a new GradeBook object Dim gradeBook As New GradeBook()

' call gradeBook's DisplayMessage method gradeBook.DisplayMessage() End Sub ' MainEnd Module

Object variable gradeBook

Class GradeBookNew keyword will create an instance of class GradeBook

Visual Basic 2005

Introduction to Classes and Objects

Page 10: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Instance Variables and PropertiesInstance Variables and Properties

Variables declared in the body of a particular method are local variables and can be used only in that method

When a method terminates, the values of its local variables are lost

In contrast, an object's attributes are carried with the object as it is used in a program

OBJECT-ORIENTED PROGRAMMING 10

Visual Basic 2005

Introduction to Classes and Objects

Page 11: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Instance Variables and PropertiesInstance Variables and Properties

GradeBook class with instance variable and property

OBJECT-ORIENTED PROGRAMMING 11

Visual Basic 2005

' Class declaration with one method.Public Class GradeBook Private courseNameValue As String ' course name for this GradeBook

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

' display a welcome message to the GradeBook user Public Sub DisplayMessage() ' use property CourseName to display the ' name of the course this GradeBook represents Console.WriteLine("Welcome to the grade book for " _ & vbCrLf & CourseName & "!") End Sub ' DisplayMessageEnd Class

' Class declaration with one method.Public Class GradeBook Private courseNameValue As String ' course name for this GradeBook

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

' display a welcome message to the GradeBook user Public Sub DisplayMessage() ' use property CourseName to display the ' name of the course this GradeBook represents Console.WriteLine("Welcome to the grade book for " _ & vbCrLf & CourseName & "!") End Sub ' DisplayMessageEnd Class

Property CourseName

Instance variable courseNameValue

Introduction to Classes and Objects

Page 12: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Instance Variables and PropertiesInstance Variables and Properties

Most instance variable declarations are preceded with the access modifier Private

Declaring instance variables with access modifier Private is known as information hiding

When a program creates (instantiates) an object of class GradeBook, variable courseNameValue is encapsulated (hidden) in the object and can be accessed only by methods and properties of the object's class

OBJECT-ORIENTED PROGRAMMING 12

Visual Basic 2005

Introduction to Classes and Objects

Page 13: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Instance Variables and PropertiesInstance Variables and Properties

The Get accessor begins with the keyword Get and ends with the keywords End Get

The Get accessor returns the value to the client code that references the property

The Get accessor's body contains a Return statement

OBJECT-ORIENTED PROGRAMMING 13

Visual Basic 2005

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

Get accessor

Introduction to Classes and Objects

Page 14: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Instance Variables and PropertiesInstance Variables and Properties

The Set accessor begins with the keyword Set and ends with the keywords End Set

The Set accessor stores the value into the instance variable from a client code that references the property

OBJECT-ORIENTED PROGRAMMING 14

Visual Basic 2005

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

Set accessor

Introduction to Classes and Objects

Page 15: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Initializing Objects with ConstructorsInitializing Objects with Constructors

Each class you declare can provide a constructor that can be used to initialize an object of the class when the object is created

The New keyword calls the class's constructor to perform the initialization

The constructor call is indicated by the class name followed by parentheses

OBJECT-ORIENTED PROGRAMMING 15

Visual Basic 2005

Introduction to Classes and Objects

Page 16: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Initializing Objects with ConstructorsInitializing Objects with Constructors

GradeBook class with a constructor

OBJECT-ORIENTED PROGRAMMING 16

Visual Basic 2005

' Class declaration with one method.Public Class GradeBook Private courseNameValue As String ' course name for this GradeBook

Public Sub New(ByVal name As String) CourseName = name End Sub

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

. . .End Class

' Class declaration with one method.Public Class GradeBook Private courseNameValue As String ' course name for this GradeBook

Public Sub New(ByVal name As String) CourseName = name End Sub

' property CourseName Public Property CourseName() As String Get ' retrieve courseNameValue Return courseNameValue End Get

Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object End Set End Property ' CourseName

. . .End Class

Class constructor

Introduction to Classes and Objects

Page 17: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Initializing Objects with ConstructorsInitializing Objects with Constructors

Constructor used to initialize GradeBook objects

OBJECT-ORIENTED PROGRAMMING 17

Module GradeBookTest ' Main begins program execution Sub Main() ' create GradeBook object Dim gradeBook1 As New GradeBook( _ "CS101 Introduction to Visual Basic Programming") Dim gradeBook2 As New GradeBook( _ "CS102 Data Structures in Visual Basic")

' display initial value of CourseName for each GradeBook Console.WriteLine( _ "gradeBook1 course name is: " & gradeBook1.CourseName) Console.WriteLine( _ "gradeBook2 course name is: " & gradeBook2.CourseName) End Sub ' Main End Module ' GradeBookTest

Module GradeBookTest ' Main begins program execution Sub Main() ' create GradeBook object Dim gradeBook1 As New GradeBook( _ "CS101 Introduction to Visual Basic Programming") Dim gradeBook2 As New GradeBook( _ "CS102 Data Structures in Visual Basic")

' display initial value of CourseName for each GradeBook Console.WriteLine( _ "gradeBook1 course name is: " & gradeBook1.CourseName) Console.WriteLine( _ "gradeBook2 course name is: " & gradeBook2.CourseName) End Sub ' Main End Module ' GradeBookTest

Introduction to Classes and Objects

Page 18: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Object-Oriented Programming: Object-Oriented Programming: InheritanceInheritanceObjectives

OBJECT-ORIENTED PROGRAMMING 18

In this chapter you will learn:•What inheritance is and how it promotes software reusability.•The notions of base classes and derived classes.•To use keyword Inherits to create a class that inherits attributes and behaviors from another class.•To use the access modifier Protected in a base class to give derived class methods access to base class members.•To access base class members from a derived class with MyBase.•How constructors are used in inheritance hierarchies.•To access the current object with Me and MyClass.•The methods of class Object the direct or indirect base class of all classes in Visual Basic.

Visual Basic 2005

Page 19: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

OverviewOverview

Inheritance is a form of software reuse in which a new class is created by absorbing an existing class's members and embellishing them with new or modified capabilities

With inheritance, you can save time during program development by reusing proven and debugged high-quality software

19OBJECT-ORIENTED PROGRAMMING

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 20: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

OverviewOverview

The existing class is called the base class (superclass in Java)

The new class is the derived class (subclass in Java)

Derived class can become the base class for future derived classes

A derived class is more specific than its base class and represents a more specialized group of objects

20OBJECT-ORIENTED PROGRAMMING

Visual Basic 2005

Object-Oriented Programming: Inheritance

Page 21: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Base Classes and Derived ClassesBase Classes and Derived Classes

Often, an object of one class is an object of another class as well

For example, in geometry, a rectangle is a quadrilateral

Thus, in Visual Basic, class Rectangle can be said to inherit from class Quadrilateral

In this context, class Quadrilateral is a base class and class Rectangle is a derived class

21OBJECT-ORIENTED PROGRAMMING

Visual Basic 2005

Object-Oriented Programming: Inheritance

Page 22: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Base Classes and Derived ClassesBase Classes and Derived Classes

Inheritance examples:

22OBJECT-ORIENTED PROGRAMMING

Visual Basic 2005

Base Class Derived Classes

Student GraduateStudent, UndergraduateStudent

Shape Circle, Triangle, Rectangle

Loan CarLoan, HomeImprovementLoan, MortgageLoan

Employee Faculty, Staff

BankAccount CheckingAccount, SavingsAccount

Object-Oriented Programming: Inheritance

Page 23: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Base Classes and Derived ClassesBase Classes and Derived Classes

Inheritance hierarchy

23OBJECT-ORIENTED PROGRAMMING

Visual Basic 2005

ShapeShape

TwoDimensionalShapeTwoDimensionalShape ThreeDimensionalShapeThreeDimensionalShape

SquareSquareCircleCircle TriangleTriangle CubeCubeSphereSphere TetrahedronTetrahedron

Object-Oriented Programming: Inheritance

Page 24: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

ProtectedProtected Members Members

Protected access offers an intermediate level of access between Public and Private access

A base class's Protected members can be accessed only by members of that base class and by members of its derived classes

All Public and Protected base class members retain their original access modifier when they become members of the derived class

24OBJECT-ORIENTED PROGRAMMING

Visual Basic 2005

Object-Oriented Programming: Inheritance

Page 25: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

CommissionEmployee class with Protected instance variables

25OBJECT-ORIENTED PROGRAMMING

Visual Basic 2005

Object-Oriented Programming: Inheritance

' CommissionEmployee class represents a commission employee.Public Class CommissionEmployee

Protected firstNameValue As String ' first name Protected lastNameValue As String ' last name Protected socialSecurityNumberValue As String ' social security number Protected grossSalesValue As Decimal ' gross weekly sales Protected commissionRateValue As Decimal ' commission percentage

' five-argument constructor Public Sub New(ByVal first As String, ByVal last As String, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal rate As Decimal)

' implicit call to Object constructor occurs here FirstName = first LastName = last SocialSecurityNumber = ssn GrossSales = sales ' validate and store gross sales CommissionRate = rate ' validate and store commission rate End Sub ' New. . .continued

' CommissionEmployee class represents a commission employee.Public Class CommissionEmployee

Protected firstNameValue As String ' first name Protected lastNameValue As String ' last name Protected socialSecurityNumberValue As String ' social security number Protected grossSalesValue As Decimal ' gross weekly sales Protected commissionRateValue As Decimal ' commission percentage

' five-argument constructor Public Sub New(ByVal first As String, ByVal last As String, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal rate As Decimal)

' implicit call to Object constructor occurs here FirstName = first LastName = last SocialSecurityNumber = ssn GrossSales = sales ' validate and store gross sales CommissionRate = rate ' validate and store commission rate End Sub ' New. . .continued

Page 26: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

CommissionEmployee class with Protected instance variables

OBJECT-ORIENTED PROGRAMMING 26

Visual Basic 2005

Object-Oriented Programming: Inheritance

' property FirstName Public Property FirstName() As String Get Return firstNameValue End Get Set(ByVal first As String) firstNameValue = first ' no validation End Set End Property ' FirstName

' property LastName Public Property LastName() As String Get Return lastNameValue End Get Set(ByVal last As String) lastNameValue = last ' no validation End Set End Property ' LastName. . .continued

' property FirstName Public Property FirstName() As String Get Return firstNameValue End Get Set(ByVal first As String) firstNameValue = first ' no validation End Set End Property ' FirstName

' property LastName Public Property LastName() As String Get Return lastNameValue End Get Set(ByVal last As String) lastNameValue = last ' no validation End Set End Property ' LastName. . .continued

Page 27: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

CommissionEmployee class with Protected instance variables

OBJECT-ORIENTED PROGRAMMING 27

Visual Basic 2005

Object-Oriented Programming: Inheritance

' property SocialSecurityNumber Public Property SocialSecurityNumber() As String Get Return socialSecurityNumberValue End Get Set(ByVal ssn As String) socialSecurityNumberValue = ssn ' no validation End Set End Property ' SocialSecurityNumber

' property GrossSales Public Property GrossSales() As Decimal Get Return grossSalesValue End Get Set(ByVal sales As Decimal) If sales < 0.0 Then ' validate gross sales grossSalesValue = 0 Else grossSalesValue = sales End If End Set End Property ' GrossSales. . .continued

' property SocialSecurityNumber Public Property SocialSecurityNumber() As String Get Return socialSecurityNumberValue End Get Set(ByVal ssn As String) socialSecurityNumberValue = ssn ' no validation End Set End Property ' SocialSecurityNumber

' property GrossSales Public Property GrossSales() As Decimal Get Return grossSalesValue End Get Set(ByVal sales As Decimal) If sales < 0.0 Then ' validate gross sales grossSalesValue = 0 Else grossSalesValue = sales End If End Set End Property ' GrossSales. . .continued

Page 28: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

CommissionEmployee class with Protected instance variables

OBJECT-ORIENTED PROGRAMMING 28

Visual Basic 2005

Object-Oriented Programming: Inheritance

' property CommissionRate Public Property CommissionRate() As Decimal Get Return commissionRateValue End Get

Set(ByVal rate As Decimal) If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate commissionRateValue = rate Else commissionRateValue = 0 End If End Set End Property ' CommissionRate

' calculate earnings Public Overridable Function CalculateEarnings() As Decimal Return commissionRateValue * grossSalesValue End Function ' CalculateEarnings. . .continued

' property CommissionRate Public Property CommissionRate() As Decimal Get Return commissionRateValue End Get

Set(ByVal rate As Decimal) If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate commissionRateValue = rate Else commissionRateValue = 0 End If End Set End Property ' CommissionRate

' calculate earnings Public Overridable Function CalculateEarnings() As Decimal Return commissionRateValue * grossSalesValue End Function ' CalculateEarnings. . .continued

Page 29: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

CommissionEmployee class with Protected instance variables

OBJECT-ORIENTED PROGRAMMING 29

Visual Basic 2005

Object-Oriented Programming: Inheritance

' return String representation of CommissionEmployee object Public Overrides Function ToString() As String Return ("commission employee: " & firstNameValue & " " & _ lastNameValue & vbCrLf & "social security number: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ "commission rate: " & String.Format("{0:F}", _ commissionRateValue)) End Function ' ToStringEnd Class

' return String representation of CommissionEmployee object Public Overrides Function ToString() As String Return ("commission employee: " & firstNameValue & " " & _ lastNameValue & vbCrLf & "social security number: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ "commission rate: " & String.Format("{0:F}", _ commissionRateValue)) End Function ' ToStringEnd Class

Page 30: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee

OBJECT-ORIENTED PROGRAMMING 30

Public Class BasePlusCommissionEmployee Inherits CommissionEmployee

Private baseSalaryValue As Decimal ' base salary per week

' six-argument constructor Public Sub New(ByVal first As String, ByVal last As String, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal rate As Decimal, ByVal salary As Decimal)

' use MyBase reference to CommissionEmployee constructor explicitly MyBase.New(first, last, ssn, sales, rate) BaseSalary = salary ' validate and store base salary End Sub ' New. . .continued

Public Class BasePlusCommissionEmployee Inherits CommissionEmployee

Private baseSalaryValue As Decimal ' base salary per week

' six-argument constructor Public Sub New(ByVal first As String, ByVal last As String, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal rate As Decimal, ByVal salary As Decimal)

' use MyBase reference to CommissionEmployee constructor explicitly MyBase.New(first, last, ssn, sales, rate) BaseSalary = salary ' validate and store base salary End Sub ' New. . .continued

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 31: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee

OBJECT-ORIENTED PROGRAMMING 31

' property BaseSalary Public Property BaseSalary() As Decimal Get Return baseSalaryValue End Get

Set(ByVal salary As Decimal) If salary < 0.0 Then ' validate base salary baseSalaryValue = 0 Else baseSalaryValue = salary End If End Set End Property ' BaseSalary

. . .continued

' property BaseSalary Public Property BaseSalary() As Decimal Get Return baseSalaryValue End Get

Set(ByVal salary As Decimal) If salary < 0.0 Then ' validate base salary baseSalaryValue = 0 Else baseSalaryValue = salary End If End Set End Property ' BaseSalary

. . .continued

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 32: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee

OBJECT-ORIENTED PROGRAMMING 32

' calculate earnings Public Overrides Function CalculateEarnings() As Decimal Return baseSalaryValue + (commissionRateValue * grossSalesValue) End Function ' CalculateEarnings

' return String representation of BasePlusCommissionEmployee object Public Overrides Function ToString() As String Return ("base-plus-commission employee: " & firstNameValue & " " & _ lastNameValue & vbCrLf & "social security number: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ "commission rate: " & String.Format("{0:F}", _ commissionRateValue) & vbCrLf & "base salary: " & _ String.Format("{0:C}", baseSalaryValue)) End Function ' ToStringEnd Class

' calculate earnings Public Overrides Function CalculateEarnings() As Decimal Return baseSalaryValue + (commissionRateValue * grossSalesValue) End Function ' CalculateEarnings

' return String representation of BasePlusCommissionEmployee object Public Overrides Function ToString() As String Return ("base-plus-commission employee: " & firstNameValue & " " & _ lastNameValue & vbCrLf & "social security number: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ "commission rate: " & String.Format("{0:F}", _ commissionRateValue) & vbCrLf & "base salary: " & _ String.Format("{0:C}", baseSalaryValue)) End Function ' ToStringEnd Class

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 33: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

Testing class BasePlusCommissionEmployee

OBJECT-ORIENTED PROGRAMMING 33

Module BasePlusCommissionEmployeeTest Sub Main() ' instantiate BasePlusCommissionEmployee object Dim employee As New BasePlusCommissionEmployee( _ "Bob", "Lewis", "333-33-3333", 5000, 0.04D, 300)

' get base-salaried commission employee data Console.WriteLine("Employee information obtained by properties:" & _ vbCrLf & _ "First name is " & employee.FirstName & vbCrLf & _ "Last name is " & employee.LastName & vbCrLf & _ "Social Security Number is " & _ employee.SocialSecurityNumber)

Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) Console.WriteLine("Commission rate is {0:F}", employee.CommissionRate) Console.WriteLine("Base salary is {0:C}", employee.BaseSalary)

. . .continued

Module BasePlusCommissionEmployeeTest Sub Main() ' instantiate BasePlusCommissionEmployee object Dim employee As New BasePlusCommissionEmployee( _ "Bob", "Lewis", "333-33-3333", 5000, 0.04D, 300)

' get base-salaried commission employee data Console.WriteLine("Employee information obtained by properties:" & _ vbCrLf & _ "First name is " & employee.FirstName & vbCrLf & _ "Last name is " & employee.LastName & vbCrLf & _ "Social Security Number is " & _ employee.SocialSecurityNumber)

Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) Console.WriteLine("Commission rate is {0:F}", employee.CommissionRate) Console.WriteLine("Base salary is {0:C}", employee.BaseSalary)

. . .continued

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 34: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Relationship Between Base Classes and Relationship Between Base Classes and Derived ClassesDerived Classes

Testing class BasePlusCommissionEmployee

OBJECT-ORIENTED PROGRAMMING 34

employee.BaseSalary = 1000 ' set base salary

' get new employee information Console.WriteLine(vbCrLf & _ "Updated employee information obtained by ToString: " & _ vbCrLf & employee.ToString() & vbCrLf)

' display the employee's earnings Console.WriteLine("Employee's earnings: $" & _ employee.CalculateEarnings()) Console.Read() End Sub ' MainEnd Module

employee.BaseSalary = 1000 ' set base salary

' get new employee information Console.WriteLine(vbCrLf & _ "Updated employee information obtained by ToString: " & _ vbCrLf & employee.ToString() & vbCrLf)

' display the employee's earnings Console.WriteLine("Employee's earnings: $" & _ employee.CalculateEarnings()) Console.Read() End Sub ' MainEnd Module

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 35: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Class ObjectClass Object

All classes inherit directly or indirectly from the Object class (namespace System)

So the Object’s seven methods are inherited by all other classes◦Equals()◦Finalize()◦GetHashCode()◦GetType()◦MemberwiseClone()◦ReferenceEquals()◦ToString()

OBJECT-ORIENTED PROGRAMMING 35

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 36: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

FriendFriend Members Members

Another intermediate level of member access is Friend access

A class's Friend members can be accessed only by code in the same assembly

Unlike Public access, any other programs that are declared outside the assembly cannot access these Friend members

OBJECT-ORIENTED PROGRAMMING 36

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 37: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

FriendFriend Members Members

Showing accessibility of Friend members

OBJECT-ORIENTED PROGRAMMING 37

Assembly 1

Assembly 2

BlogAccount

ClassInSamePackage~countEntries()aMethod()

SpecializedClassInAnotherPackageClassInAnotherPackage

countEntries is a Friend method

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 38: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

FriendFriend Members Members

Showing accessibility of Friend members

OBJECT-ORIENTED PROGRAMMING 38

ClassLibrary1 assembly

(DLL)

ClassLibrary2Assembly

(DLL)

FriendAccessTestAssembly

(EXE)

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 39: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

FriendFriend Members Members

Showing accessibility of Friend members

OBJECT-ORIENTED PROGRAMMING 39

Friend instance variable data1

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 40: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

FriendFriend Members Members

Showing accessibility of Friend members

OBJECT-ORIENTED PROGRAMMING 40

Accessing a Friend member within the same assembly is

allowed

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 41: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

FriendFriend Members Members

Showing accessibility of Friend members

OBJECT-ORIENTED PROGRAMMING 41

Attempting to access Friend member in another assembly

produces an error

Object-Oriented Programming: Inheritance

Visual Basic 2005

Page 42: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Object-Oriented Programming: Object-Oriented Programming: PolymorphismPolymorphismObjectives

OBJECT-ORIENTED PROGRAMMING 42

In this chapter you will learn:•What polymorphism is.•To use overridden methods to effect polymorphism.•To distinguish between abstract and concrete classes.•To declare abstract methods to create abstract classes.•How polymorphism makes systems extensible and maintainable.•To determine an object's type at execution time.•To declare and implement interfaces.

Visual Basic 2005

Page 43: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

OverviewOverview

Polymorphism enables us to "program in the general" rather than "program in the specific”

In particular, polymorphism enables us to write programs that process objects that share the same base class in a class hierarchy as simply as if they were all objects of the base class

OBJECT-ORIENTED PROGRAMMING 43

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 44: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

OverviewOverview

With polymorphism, we can design and implement systems that are easily extensible new classes can be added with little or no modification to the general portions of the program

OBJECT-ORIENTED PROGRAMMING 44

Visual Basic 2005

Object-Oriented Programming: Polymorphism

AnimalAnimal

The base class animal implements a method eat.

Each of these animals implement their own way of

eating.

Page 45: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Demonstrating Polymorphic BehaviorDemonstrating Polymorphic Behavior

Implementing the Animal hierarchy

OBJECT-ORIENTED PROGRAMMING 45

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Public Class Animal

Public Overridable Sub Eat() Console.WriteLine("Animal: Eat") End SubEnd Class

Public Class Animal

Public Overridable Sub Eat() Console.WriteLine("Animal: Eat") End SubEnd Class

Public Class Bird Inherits Animal

Public Overrides Sub Eat() Console.WriteLine("Bird: Eat") End SubEnd Class

Public Class Bird Inherits Animal

Public Overrides Sub Eat() Console.WriteLine("Bird: Eat") End SubEnd Class

Public Class Fish Inherits Animal

Public Overrides Sub Eat() Console.WriteLine("Fish: Eat") End SubEnd Class

Public Class Fish Inherits Animal

Public Overrides Sub Eat() Console.WriteLine("Fish: Eat") End SubEnd Class

Inherits keyword enables

inheritance

Overrides keyword

replaces the implementation

of the base class

Overridable keyword allows derived classes

to implement their own behavior

Page 46: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Demonstrating Polymorphic BehaviorDemonstrating Polymorphic Behavior

Implementing the Animal hierarchy

OBJECT-ORIENTED PROGRAMMING 46

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Public Class Dog Inherits Animal

Public Overrides Sub Eat() Console.WriteLine("Dog: Eat") End SubEnd Class

Public Class Dog Inherits Animal

Public Overrides Sub Eat() Console.WriteLine("Dog: Eat") End SubEnd Class

Module ModPolymorphTest Sub Main() Dim Hayop As Animal Dim bantay As New Dog, tweety As New Bird, nemo As New Fish

Hayop = bantay ‘set Hayop to reference bantay Hayop.Eat()

Hayop = tweety ‘set Hayop to reference tweety Hayop.Eat()

Hayop = nemo ‘set Hayop to reference nemo Hayop.Eat() End SubEnd Module

Module ModPolymorphTest Sub Main() Dim Hayop As Animal Dim bantay As New Dog, tweety As New Bird, nemo As New Fish

Hayop = bantay ‘set Hayop to reference bantay Hayop.Eat()

Hayop = tweety ‘set Hayop to reference tweety Hayop.Eat()

Hayop = nemo ‘set Hayop to reference nemo Hayop.Eat() End SubEnd Module

Inherits keyword enables

inheritance

Page 47: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Demonstrating Polymorphic BehaviorDemonstrating Polymorphic Behavior

Output:

OBJECT-ORIENTED PROGRAMMING 47

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Each of these strings is

generated by invoking different

implementations of the Eat

method referenced by

the Hayop object variable

Page 48: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Abstract Classes and MethodsAbstract Classes and Methods

Abstract classes are used to declare classes for which you never intend to instantiate objects

They are used only as base classes in inheritance hierarchies, we refer to them as abstract base classes

These classes cannot be used to instantiate objects, because abstract classes are incomplete

OBJECT-ORIENTED PROGRAMMING 48

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 49: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Abstract Classes and MethodsAbstract Classes and Methods

The purpose of an abstract class is primarily to provide an appropriate base class from which other classes can inherit and thus share a common design

To define an abstract base class:

OBJECT-ORIENTED PROGRAMMING 49

Visual Basic 2005

Object-Oriented Programming: Polymorphism

‘Abstract class EmployeePublic MustInherit Class Employee

. . . ' abstract method overridden by derived class Public MustOverride Function CalculateEarnings() As Decimal

End Class

‘Abstract class EmployeePublic MustInherit Class Employee

. . . ' abstract method overridden by derived class Public MustOverride Function CalculateEarnings() As Decimal

End Class

MustInherit keyword

MustOverride keyword A MustOverride procedure doesn’t implement any code

Page 50: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

NotOverridableNotOverridable Methods and Methods and NotInheritableNotInheritable Classes Classes

A method that is declared NotOverridable in a base class cannot be overridden in a derived class

A method that is declared Overridable in a base class can be declared NotOverridable in a derived class

Methods that are declared Private are implicitly NotOverridable

OBJECT-ORIENTED PROGRAMMING 50

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 51: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

NotOverridableNotOverridable Methods and Methods and NotInheritableNotInheritable Classes Classes

A class that is declared NotInheritable cannot be a base class

All methods in a NotInheritable class are implicitly NotOverridable

NotInheritable class is the opposite of a MustInherit class

Class String is a NotInheritable class

OBJECT-ORIENTED PROGRAMMING 51

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 52: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating and Using InterfacesCreating and Using Interfaces

Interfaces define and standardize the ways in which things such as people and systems can interact with one another

For example, the controls on a radio serve as an interface between radio users and a radio's internal components

The controls allow users to perform only a limited set of operations

OBJECT-ORIENTED PROGRAMMING 52

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 53: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating and Using InterfacesCreating and Using Interfaces

Software objects also communicate via interfaces

A Visual Basic interface describes a set of methods that can be called on an object, to tell the object to perform some task or return some piece of information

An interface is often used in place of a MustInherit class when there is no default implementation to inherit

OBJECT-ORIENTED PROGRAMMING 53

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 54: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating and Using InterfacesCreating and Using Interfaces

An interface declaration begins with the keyword Interface:

OBJECT-ORIENTED PROGRAMMING 54

Visual Basic 2005

Object-Oriented Programming: Polymorphism

' IPayable interface declaration. Public Interface IPayable

Function GetPaymentAmount() As Decimal ' calculate payment Function ToString() As String ' display Payable object

End Interface ' IPayable

' IPayable interface declaration. Public Interface IPayable

Function GetPaymentAmount() As Decimal ' calculate payment Function ToString() As String ' display Payable object

End Interface ' IPayable

Interface members will not have any implementation

Interface keyword

Page 55: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating and Using InterfacesCreating and Using Interfaces

IPayable interface hierarchy

OBJECT-ORIENTED PROGRAMMING 55

Visual Basic 2005

Object-Oriented Programming: Polymorphism

<<interface>>IPayable

<<interface>>IPayable

InvoiceInvoice EmployeeEmployee

SalariedEmployeeSalariedEmployee

Page 56: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

Creating and Using InterfacesCreating and Using Interfaces

Using the interface

OBJECT-ORIENTED PROGRAMMING 56

Visual Basic 2005

Object-Oriented Programming: Polymorphism

' IPayable interface declaration. Public Class Invoice Implements IPayable

Public Function GetPaymentAmount() As Decimal _ Implements IPayable.GetPaymentAmount ‘implementation here End Function

Public Function ToString1() As String _ Implements IPayable.ToString ‘implementation here End Function

. . .

End Class ' Invoice

' IPayable interface declaration. Public Class Invoice Implements IPayable

Public Function GetPaymentAmount() As Decimal _ Implements IPayable.GetPaymentAmount ‘implementation here End Function

Public Function ToString1() As String _ Implements IPayable.ToString ‘implementation here End Function

. . .

End Class ' Invoice

Implements keyword

Interface IPayable

Classes that implements the IPayable should include the methods defined in

the interface

Page 57: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

ExerciseExerciseOBJECT-ORIENTED PROGRAMMING 57

Visual Basic 2005

Object-Oriented Programming: Polymorphism

Page 58: MELJUN CORTES Visual Basic 2005  Object-Oriented Programming

End of Object-Oriented End of Object-Oriented ProgrammingProgramming

OBJECT-ORIENTED PROGRAMMING 58

Visual Basic 2005

Object-Oriented Programming: Polymorphism