Visual Basic 2005
V. OBJECT-ORIENTED PROGRAMMING

MELJUN CORTES
In this chapter you will learn:
•What classes, objects, methods, instance variables and properties are.
•How to declare a ...
Introduction to Classes and Objects

Object

orientation uses classes to
encapsulate instance variables (data) and
method...
Introduction to Classes and Objects

A

class is a type of something
You can think of a class as being the
blueprint out...
Introduction to Classes and Objects

An

object is an instance of a class
For example, you may have several
instances of...
Introduction to Classes and Objects

Class

vs. Object

Car Blueprint (Class)

Actual Cars (Objects)

Classes vs Objects
...
Introduction to Classes and Objects

You

can add a class from Project menu
and selecting the Add Class item or by
right-...
Introduction to Classes and Objects

Class

declaration with one method

' Class declaration with one method.
' Class dec...
Introduction to Classes and Objects

Creating

an object of class GradeBook

Module ModGradeBookTest
Module ModGradeBookT...
Introduction to Classes and Objects

Variables

declared in the body of a
particular method are local variables and
can b...
Introduction to Classes and Objects

class with instance variable
and property

GradeBook

Instance variable
courseNameVa...
Introduction to Classes and Objects

Most

instance variable declarations are
preceded with the access modifier Private
...
Introduction to Classes and Objects

The

Get accessor begins with the keyword
Get and ends with the keywords End Get
Th...
Introduction to Classes and Objects

The

Set accessor begins with the keyword
Set and ends with the keywords End Set
Th...
Introduction to Classes and Objects

Each

class you declare can provide a
constructor that can be used to initialize
an ...
Introduction to Classes and Objects

GradeBook

class with a constructor

' Class declaration with one method.
' Class de...
Introduction to Classes and Objects

Constructor

objects

used to initialize GradeBook

Module GradeBookTest
Module Grad...
In this chapter you will learn:
•What inheritance is and how it promotes software reusability.
•The notions of base classe...
Object-Oriented Programming: Inheritance

Inheritance

is a form of software reuse
in which a new class is created by
abs...
Object-Oriented Programming: Inheritance

The

existing class is called the base class
(superclass in Java)
The new clas...
Object-Oriented Programming: Inheritance

Often,

an object of one class is an object
of another class as well
For examp...
Object-Oriented Programming: Inheritance

Inheritance

examples:

Base Class

Derived Classes

Student

GraduateStudent, ...
Object-Oriented Programming: Inheritance

Inheritance

hierarchy
Shape
Shape

TwoDimensionalShape
TwoDimensionalShape

Ci...
Object-Oriented Programming: Inheritance

access offers an intermediate
level of access between Public and Private
access
...
Object-Oriented Programming: Inheritance

 CommissionEmployee

instance variables

class with Protected

' CommissionEmpl...
Object-Oriented Programming: Inheritance


CommissionEmployee class with Protected instance
variables
' property FirstNam...
Object-Oriented Programming: Inheritance


CommissionEmployee class with Protected instance
variables
' property SocialSe...
Object-Oriented Programming: Inheritance


CommissionEmployee class with Protected instance
variables
' property Commissi...
Object-Oriented Programming: Inheritance


CommissionEmployee class with Protected instance
variables
' return String rep...
Object-Oriented Programming: Inheritance


BasePlusCommissionEmployee inherits Protected instance
variables from Commissi...
Object-Oriented Programming: Inheritance


BasePlusCommissionEmployee inherits Protected instance
variables from Commissi...
Object-Oriented Programming: Inheritance


BasePlusCommissionEmployee inherits Protected instance
variables from Commissi...
Object-Oriented Programming: Inheritance


Testing class BasePlusCommissionEmployee
Module BasePlusCommissionEmployeeTest...
Object-Oriented Programming: Inheritance


Testing class BasePlusCommissionEmployee
employee.BaseSalary = 1000 ' set base...
Object-Oriented Programming: Inheritance

All

classes inherit directly or indirectly from
the Object class (namespace Sy...
Object-Oriented Programming: Inheritance

Another

intermediate level of member
access is Friend access
A class's Friend...
Object-Oriented Programming: Inheritance

Showing

accessibility of Friend members

countEntries is a
Friend method

Asse...
Object-Oriented Programming: Inheritance

Showing

accessibility of Friend members

ClassLibrary1
assembly
(DLL)

ClassLi...
Object-Oriented Programming: Inheritance

Showing

accessibility of Friend members

Friend instance
variable data1

Frien...
Object-Oriented Programming: Inheritance

Showing

accessibility of Friend members

Accessing a Friend member
within the ...
Object-Oriented Programming: Inheritance

Showing

accessibility of Friend members

Attempting to access Friend
member in...
In this chapter you will learn:
•What polymorphism is.
•To use overridden methods to effect polymorphism.
•To distinguish ...
Object-Oriented Programming: Polymorphism

Polymorphism

enables us to "program in
the general" rather than "program in t...
Object-Oriented Programming: Polymorphism

With

polymorphism, we can design and
implement systems that are easily
extens...
Object-Oriented Programming: Polymorphism

Implementing
Overridable
keyword allows
derived classes
to implement
their own...
Object-Oriented Programming: Polymorphism

Implementing

the Animal hierarchy

Public Class Dog
Public Class Dog
Inherits...
Object-Oriented Programming: Polymorphism

Output:
Each of these
strings is
generated by
invoking
different
implementatio...
Object-Oriented Programming: Polymorphism

Abstract

classes are used to declare
classes for which you never intend to
in...
Object-Oriented Programming: Polymorphism

The

purpose of an abstract class is
primarily to provide an appropriate base
...
Object-Oriented Programming: Polymorphism

A

method that is declared
NotOverridable in a base class cannot be
overridden...
Object-Oriented Programming: Polymorphism

A

class that is declared NotInheritable
cannot be a base class
All methods i...
Object-Oriented Programming: Polymorphism

Interfaces

define and standardize the
ways in which things such as people and...
Object-Oriented Programming: Polymorphism

Software

objects also communicate via
interfaces
A Visual Basic interface de...
Object-Oriented Programming: Polymorphism

An

interface declaration begins with the
keyword Interface:
Interface keyword...
Object-Oriented Programming: Polymorphism

IPayable

interface hierarchy
<<interface>>
<<interface>>
IPayable
IPayable

I...
Object-Oriented Programming: Polymorphism

Using

the interface

Implements
keyword
Interface
IPayable

' IPayable interf...
Object-Oriented Programming: Polymorphism

Exercise
OBJECT-ORIENTED
PROGRAMMING

Visual Basic 2005

57
Object-Oriented Programming: Polymorphism

End of Object-Oriented
Programming
OBJECT-ORIENTED
PROGRAMMING

Visual Basic 20...
Upcoming SlideShare
Loading in …5
×

MELJUN CORTES Visual Basic 2005 Object-Oriented Programming

262
-1

Published on

MELJUN CORTES Visual Basic 2005 Object-Oriented Programming

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
262
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

MELJUN CORTES Visual Basic 2005 Object-Oriented Programming

  1. 1. Visual Basic 2005 V. OBJECT-ORIENTED PROGRAMMING MELJUN CORTES
  2. 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 Introduction to Classes and Objects Objectives OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 2
  3. 3. Introduction to Classes and Objects 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 Overview OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 3
  4. 4. Introduction to Classes and Objects A class is a type of something You can think of a class as being the blueprint out of which objects can be constructed Car Blueprint (Class) Classes vs Objects OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 4
  5. 5. Introduction to Classes and Objects An object is an instance of a class For example, you may have several instances of a class named Car Each instance of Car is an object and may be given its own name Actual Cars (Objects) Classes vs Objects OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 5
  6. 6. Introduction to Classes and Objects Class vs. Object Car Blueprint (Class) Actual Cars (Objects) Classes vs Objects OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 6
  7. 7. Introduction to Classes and Objects 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 Click Add Class menu item to create a class in your project Creating a Class OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 7
  8. 8. Introduction to Classes and Objects Class declaration with one method ' Class declaration with one method. ' Class declaration with one method. Public Class GradeBook Public Class GradeBook ' display a welcome message to the GradeBook user ' display a welcome message to the GradeBook user Public Sub DisplayMessage() Public Sub DisplayMessage() Console.WriteLine("Welcome to the Grade Book!") Console.WriteLine("Welcome to the Grade Book!") End Sub ' DisplayMessage End Sub ' DisplayMessage End Class End Class Class keyword DisplayMessage is a method of Class GradeBook Creating a Class OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 8
  9. 9. Introduction to Classes and Objects Creating an object of class GradeBook Module ModGradeBookTest Module ModGradeBookTest ' Main begins program execution ' Main begins program execution Sub Main() Sub Main() ' initialize gradeBook to refer to a new GradeBook object ' initialize gradeBook to refer to a new GradeBook object Dim gradeBook As New GradeBook() Dim gradeBook As New GradeBook() ' call gradeBook's DisplayMessage method ' call gradeBook's DisplayMessage method gradeBook.DisplayMessage() gradeBook.DisplayMessage() End Sub ' Main End Sub ' Main End Module End Module Object variable gradeBook New keyword will create an instance of class GradeBook Class GradeBook Creating a Class OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 9
  10. 10. Introduction to Classes and Objects 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 Instance Variables and Properties OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 10
  11. 11. Introduction to Classes and Objects class with instance variable and property GradeBook Instance variable courseNameValue Property CourseName ' Class declaration with one method. ' Class declaration with one method. Public Class GradeBook Public Class GradeBook Private courseNameValue As String ' course name for this GradeBook Private courseNameValue As String ' course name for this GradeBook ' property CourseName ' property CourseName Public Property CourseName() As String Public Property CourseName() As String Get ' retrieve courseNameValue Get ' retrieve courseNameValue Return courseNameValue Return courseNameValue End Get End Get Set(ByVal value As String) ' set courseNameValue Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object courseNameValue = value ' store the course name in the object End Set End Set End Property ' CourseName End Property ' CourseName ' display a welcome message to the GradeBook user ' display a welcome message to the GradeBook user Public Sub DisplayMessage() Public Sub DisplayMessage() ' use property CourseName to display the ' use property CourseName to display the ' name of the course this GradeBook represents ' name of the course this GradeBook represents Console.WriteLine("Welcome to the grade book for " _ Console.WriteLine("Welcome to the grade book for " _ & vbCrLf & CourseName & "!") & vbCrLf & CourseName & "!") End Sub ' DisplayMessage End Sub ' DisplayMessage End Class End Class Instance Variables and Properties OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 11
  12. 12. Introduction to Classes and Objects 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 Instance Variables and Properties OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 12
  13. 13. Introduction to Classes and Objects 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 Get accessor ' property CourseName ' property CourseName Public Property CourseName() As String Public Property CourseName() As String Get ' retrieve courseNameValue Get ' retrieve courseNameValue Return courseNameValue Return courseNameValue End Get End Get Set(ByVal value As String) ' set courseNameValue Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object courseNameValue = value ' store the course name in the object End Set End Set End Property ' CourseName End Property ' CourseName Instance Variables and Properties OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 13
  14. 14. Introduction to Classes and Objects 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 ' property CourseName ' property CourseName Public Property CourseName() As String Public Property CourseName() As String Get ' retrieve courseNameValue Get ' retrieve courseNameValue Return courseNameValue Return courseNameValue End Get End Get Set accessor Set(ByVal value As String) ' set courseNameValue Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object courseNameValue = value ' store the course name in the object End Set End Set End Property ' CourseName End Property ' CourseName Instance Variables and Properties OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 14
  15. 15. Introduction to Classes and Objects 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 Initializing Objects with Constructors OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 15
  16. 16. Introduction to Classes and Objects GradeBook class with a constructor ' Class declaration with one method. ' Class declaration with one method. Public Class GradeBook Public Class GradeBook Private courseNameValue As String ' course name for this GradeBook Private courseNameValue As String ' course name for this GradeBook Class constructor Public Sub New(ByVal name As String) Public Sub New(ByVal name As String) CourseName = name CourseName = name End Sub End Sub ' property CourseName ' property CourseName Public Property CourseName() As String Public Property CourseName() As String Get ' retrieve courseNameValue Get ' retrieve courseNameValue Return courseNameValue Return courseNameValue End Get End Get Set(ByVal value As String) ' set courseNameValue Set(ByVal value As String) ' set courseNameValue courseNameValue = value ' store the course name in the object courseNameValue = value ' store the course name in the object End Set End Set End Property ' CourseName End Property ' CourseName . . . . . . End Class End Class Initializing Objects with Constructors OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 16
  17. 17. Introduction to Classes and Objects Constructor objects used to initialize GradeBook Module GradeBookTest Module GradeBookTest ' Main begins program execution ' Main begins program execution Sub Main() Sub Main() ' create GradeBook object ' create GradeBook object Dim gradeBook1 As New GradeBook( _ Dim gradeBook1 As New GradeBook( _ "CS101 Introduction to Visual Basic Programming") "CS101 Introduction to Visual Basic Programming") Dim gradeBook2 As New GradeBook( _ Dim gradeBook2 As New GradeBook( _ "CS102 Data Structures in Visual Basic") "CS102 Data Structures in Visual Basic") ' display initial value of CourseName ' display initial value of CourseName Console.WriteLine( _ Console.WriteLine( _ "gradeBook1 course name is: " & "gradeBook1 course name is: " & Console.WriteLine( _ Console.WriteLine( _ "gradeBook2 course name is: " & "gradeBook2 course name is: " & End Sub ' Main End Sub ' Main End Module ' GradeBookTest End Module ' GradeBookTest for each GradeBook for each GradeBook gradeBook1.CourseName) gradeBook1.CourseName) gradeBook2.CourseName) gradeBook2.CourseName) Initializing Objects with Constructors OBJECT-ORIENTED PROGRAMMING 17
  18. 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. Object-Oriented Programming: Inheritance Objectives OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 18
  19. 19. Object-Oriented Programming: Inheritance 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 Overview OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 19
  20. 20. Object-Oriented Programming: Inheritance 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 Overview OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 20
  21. 21. Object-Oriented Programming: Inheritance 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 Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 21
  22. 22. Object-Oriented Programming: Inheritance Inheritance examples: Base Class Derived Classes Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan, MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount, SavingsAccount Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 22
  23. 23. Object-Oriented Programming: Inheritance Inheritance hierarchy Shape Shape TwoDimensionalShape TwoDimensionalShape Circle Circle Square Square Triangle Triangle ThreeDimensionalShape ThreeDimensionalShape Sphere Sphere Cube Cube Tetrahedron Tetrahedron Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 23
  24. 24. Object-Oriented Programming: Inheritance 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 Protected Protected Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 24
  25. 25. Object-Oriented Programming: Inheritance  CommissionEmployee instance variables class with Protected ' CommissionEmployee class represents a commission employee. ' CommissionEmployee class represents a commission employee. Public Class CommissionEmployee Public Class CommissionEmployee Protected Protected Protected Protected Protected Protected Protected Protected Protected Protected firstNameValue As String ' first name firstNameValue As String ' first name lastNameValue As String ' last name lastNameValue As String ' last name socialSecurityNumberValue As String ' social security number socialSecurityNumberValue As String ' social security number grossSalesValue As Decimal ' gross weekly sales grossSalesValue As Decimal ' gross weekly sales commissionRateValue As Decimal ' commission percentage commissionRateValue As Decimal ' commission percentage ' five-argument constructor ' five-argument constructor Public Sub New(ByVal first As String, ByVal last As String, _ Public Sub New(ByVal first As String, ByVal last As String, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal rate As Decimal) ByVal rate As Decimal) ' implicit call to Object constructor occurs here ' implicit call to Object constructor occurs here FirstName = first FirstName = first LastName = last LastName = last SocialSecurityNumber = ssn SocialSecurityNumber = ssn GrossSales = sales ' validate and store gross sales GrossSales = sales ' validate and store gross sales CommissionRate = rate ' validate and store commission rate CommissionRate = rate ' validate and store commission rate End Sub ' New End Sub ' New .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 25
  26. 26. Object-Oriented Programming: Inheritance  CommissionEmployee class with Protected instance variables ' property FirstName ' property FirstName Public Property FirstName() As String Public Property FirstName() As String Get Get Return firstNameValue Return firstNameValue End Get End Get Set(ByVal first As String) Set(ByVal first As String) firstNameValue = first ' no validation firstNameValue = first ' no validation End Set End Set End Property ' FirstName End Property ' FirstName ' property LastName ' property LastName Public Property LastName() As String Public Property LastName() As String Get Get Return lastNameValue Return lastNameValue End Get End Get Set(ByVal last As String) Set(ByVal last As String) lastNameValue = last ' no validation lastNameValue = last ' no validation End Set End Set End Property ' LastName End Property ' LastName .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 26
  27. 27. Object-Oriented Programming: Inheritance  CommissionEmployee class with Protected instance variables ' property SocialSecurityNumber ' property SocialSecurityNumber Public Property SocialSecurityNumber() As String Public Property SocialSecurityNumber() As String Get Get Return socialSecurityNumberValue Return socialSecurityNumberValue End Get End Get Set(ByVal ssn As String) Set(ByVal ssn As String) socialSecurityNumberValue = ssn ' no validation socialSecurityNumberValue = ssn ' no validation End Set End Set End Property ' SocialSecurityNumber End Property ' SocialSecurityNumber ' property GrossSales ' property GrossSales Public Property GrossSales() As Decimal Public Property GrossSales() As Decimal Get Get Return grossSalesValue Return grossSalesValue End Get End Get Set(ByVal sales As Decimal) Set(ByVal sales As Decimal) If sales < 0.0 Then ' validate gross sales If sales < 0.0 Then ' validate gross sales grossSalesValue = 0 grossSalesValue = 0 Else Else grossSalesValue = sales grossSalesValue = sales End If End If End Set End Set End Property ' GrossSales End Property ' GrossSales .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 27
  28. 28. Object-Oriented Programming: Inheritance  CommissionEmployee class with Protected instance variables ' property CommissionRate ' property CommissionRate Public Property CommissionRate() As Decimal Public Property CommissionRate() As Decimal Get Get Return commissionRateValue Return commissionRateValue End Get End Get Set(ByVal rate As Decimal) Set(ByVal rate As Decimal) If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate commissionRateValue = rate commissionRateValue = rate Else Else commissionRateValue = 0 commissionRateValue = 0 End If End If End Set End Set End Property ' CommissionRate End Property ' CommissionRate ' calculate earnings ' calculate earnings Public Overridable Function CalculateEarnings() As Decimal Public Overridable Function CalculateEarnings() As Decimal Return commissionRateValue * grossSalesValue Return commissionRateValue * grossSalesValue End Function ' CalculateEarnings End Function ' CalculateEarnings .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 28
  29. 29. Object-Oriented Programming: Inheritance  CommissionEmployee class with Protected instance variables ' return String representation of CommissionEmployee object ' return String representation of CommissionEmployee object Public Overrides Function ToString() As String Public Overrides Function ToString() As String Return ("commission employee: " & firstNameValue & " " & _ Return ("commission employee: " & firstNameValue & " " & _ lastNameValue & vbCrLf & "social security number: " & _ lastNameValue & vbCrLf & "social security number: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ "commission rate: " & String.Format("{0:F}", _ "commission rate: " & String.Format("{0:F}", _ commissionRateValue)) commissionRateValue)) End Function ' ToString End Function ' ToString End Class End Class Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 29
  30. 30. Object-Oriented Programming: Inheritance  BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee Public Class BasePlusCommissionEmployee Public Class BasePlusCommissionEmployee Inherits CommissionEmployee Inherits CommissionEmployee Private baseSalaryValue As Decimal ' base salary per week Private baseSalaryValue As Decimal ' base salary per week ' six-argument constructor ' six-argument constructor Public Sub New(ByVal first As String, ByVal last As String, _ Public Sub New(ByVal first As String, ByVal last As String, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal ssn As String, ByVal sales As Decimal, _ ByVal rate As Decimal, ByVal salary As Decimal) ByVal rate As Decimal, ByVal salary As Decimal) ' use MyBase reference to CommissionEmployee constructor explicitly ' use MyBase reference to CommissionEmployee constructor explicitly MyBase.New(first, last, ssn, sales, rate) MyBase.New(first, last, ssn, sales, rate) BaseSalary = salary ' validate and store base salary BaseSalary = salary ' validate and store base salary End Sub ' New End Sub ' New .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 30
  31. 31. Object-Oriented Programming: Inheritance  BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee ' property BaseSalary ' property BaseSalary Public Property BaseSalary() As Decimal Public Property BaseSalary() As Decimal Get Get Return baseSalaryValue Return baseSalaryValue End Get End Get Set(ByVal salary As Decimal) Set(ByVal salary As Decimal) If salary < 0.0 Then ' validate base salary If salary < 0.0 Then ' validate base salary baseSalaryValue = 0 baseSalaryValue = 0 Else Else baseSalaryValue = salary baseSalaryValue = salary End If End If End Set End Set End Property ' BaseSalary End Property ' BaseSalary .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 31
  32. 32. Object-Oriented Programming: Inheritance  BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee ' calculate earnings ' calculate earnings Public Overrides Function CalculateEarnings() As Decimal Public Overrides Function CalculateEarnings() As Decimal Return baseSalaryValue + (commissionRateValue * grossSalesValue) Return baseSalaryValue + (commissionRateValue * grossSalesValue) End Function ' CalculateEarnings End Function ' CalculateEarnings ' return String representation of BasePlusCommissionEmployee object ' return String representation of BasePlusCommissionEmployee object Public Overrides Function ToString() As String Public Overrides Function ToString() As String Return ("base-plus-commission employee: " & firstNameValue & " " & _ Return ("base-plus-commission employee: " & firstNameValue & " " & _ lastNameValue & vbCrLf & "social security number: " & _ lastNameValue & vbCrLf & "social security number: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ socialSecurityNumberValue & vbCrLf & "gross sales: " & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ String.Format("{0:C}", grossSalesValue) & vbCrLf & _ "commission rate: " & String.Format("{0:F}", _ "commission rate: " & String.Format("{0:F}", _ commissionRateValue) & vbCrLf & "base salary: " & _ commissionRateValue) & vbCrLf & "base salary: " & _ String.Format("{0:C}", baseSalaryValue)) String.Format("{0:C}", baseSalaryValue)) End Function ' ToString End Function ' ToString End Class End Class Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 32
  33. 33. Object-Oriented Programming: Inheritance  Testing class BasePlusCommissionEmployee Module BasePlusCommissionEmployeeTest Module BasePlusCommissionEmployeeTest Sub Main() Sub Main() ' instantiate BasePlusCommissionEmployee object ' instantiate BasePlusCommissionEmployee object Dim employee As New BasePlusCommissionEmployee( _ Dim employee As New BasePlusCommissionEmployee( _ "Bob", "Lewis", "333-33-3333", 5000, 0.04D, 300) "Bob", "Lewis", "333-33-3333", 5000, 0.04D, 300) ' get base-salaried commission employee data ' get base-salaried commission employee data Console.WriteLine("Employee information obtained by properties:" & _ Console.WriteLine("Employee information obtained by properties:" & _ vbCrLf & _ vbCrLf & _ "First name is " & employee.FirstName & vbCrLf & _ "First name is " & employee.FirstName & vbCrLf & _ "Last name is " & employee.LastName & vbCrLf & _ "Last name is " & employee.LastName & vbCrLf & _ "Social Security Number is " & _ "Social Security Number is " & _ employee.SocialSecurityNumber) employee.SocialSecurityNumber) Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) Console.WriteLine("Commission rate is {0:F}", employee.CommissionRate) Console.WriteLine("Commission rate is {0:F}", employee.CommissionRate) Console.WriteLine("Base salary is {0:C}", employee.BaseSalary) Console.WriteLine("Base salary is {0:C}", employee.BaseSalary) .. .. .continued .continued Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 33
  34. 34. Object-Oriented Programming: Inheritance  Testing class BasePlusCommissionEmployee employee.BaseSalary = 1000 ' set base salary employee.BaseSalary = 1000 ' set base salary ' get new employee information ' get new employee information Console.WriteLine(vbCrLf & _ Console.WriteLine(vbCrLf & _ "Updated employee information obtained by ToString: " & _ "Updated employee information obtained by ToString: " & _ vbCrLf & employee.ToString() & vbCrLf) vbCrLf & employee.ToString() & vbCrLf) ' display the employee's earnings ' display the employee's earnings Console.WriteLine("Employee's earnings: $" & _ Console.WriteLine("Employee's earnings: $" & _ employee.CalculateEarnings()) employee.CalculateEarnings()) Console.Read() Console.Read() End Sub ' Main End Sub ' Main End Module End Module Relationship Between Base Classes and Derived Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 34
  35. 35. Object-Oriented Programming: Inheritance 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() Class Object OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 35
  36. 36. Object-Oriented Programming: Inheritance 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 Friend Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 36
  37. 37. Object-Oriented Programming: Inheritance Showing accessibility of Friend members countEntries is a Friend method Assembly 1 BlogAccount ~countEntries() aMethod() ClassInSamePackage Assembly 2 ClassInAnotherPackage SpecializedClassInAnotherPackage Friend Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 37
  38. 38. Object-Oriented Programming: Inheritance Showing accessibility of Friend members ClassLibrary1 assembly (DLL) ClassLibrary2 Assembly (DLL) FriendAccessTest Assembly (EXE) Friend Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 38
  39. 39. Object-Oriented Programming: Inheritance Showing accessibility of Friend members Friend instance variable data1 Friend Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 39
  40. 40. Object-Oriented Programming: Inheritance Showing accessibility of Friend members Accessing a Friend member within the same assembly is allowed Friend Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 40
  41. 41. Object-Oriented Programming: Inheritance Showing accessibility of Friend members Attempting to access Friend member in another assembly produces an error Friend Members OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 41
  42. 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. Object-Oriented Programming: Polymorphism Objectives OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 42
  43. 43. Object-Oriented Programming: Polymorphism 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 Overview OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 43
  44. 44. Object-Oriented Programming: Polymorphism 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 Animal Animal The base class animal implements a method eat. Each of these animals implement their own way of eating. Overview OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 44
  45. 45. Object-Oriented Programming: Polymorphism Implementing Overridable keyword allows derived classes to implement their own behavior the Animal hierarchy Public Class Animal Public Class Animal Public Overridable Sub Eat() Public Overridable Sub Eat() Console.WriteLine("Animal: Eat") Console.WriteLine("Animal: Eat") End Sub End Sub End Class End Class Public Class Bird Public Class Bird Inherits Animal Inherits Animal Inherits keyword enables inheritance Overrides keyword replaces the implementation of the base class Public Overrides Sub Eat() Public Overrides Sub Eat() Console.WriteLine("Bird: Eat") Console.WriteLine("Bird: Eat") End Sub End Sub End Class End Class Public Class Fish Public Class Fish Inherits Animal Inherits Animal Public Overrides Sub Eat() Public Overrides Sub Eat() Console.WriteLine("Fish: Eat") Console.WriteLine("Fish: Eat") End Sub End Sub End Class End Class Demonstrating Polymorphic Behavior OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 45
  46. 46. Object-Oriented Programming: Polymorphism Implementing the Animal hierarchy Public Class Dog Public Class Dog Inherits Animal Inherits Animal Inherits keyword enables inheritance Public Overrides Sub Eat() Public Overrides Sub Eat() Console.WriteLine("Dog: Eat") Console.WriteLine("Dog: Eat") End Sub End Sub End Class End Class Module ModPolymorphTest Module ModPolymorphTest Sub Main() Sub Main() Dim Hayop As Animal Dim Hayop As Animal Dim bantay As New Dog, tweety As New Bird, nemo As New Fish Dim bantay As New Dog, tweety As New Bird, nemo As New Fish Hayop = bantay Hayop = bantay Hayop.Eat() Hayop.Eat() ‘set Hayop to reference bantay ‘set Hayop to reference bantay Hayop = tweety Hayop = tweety Hayop.Eat() Hayop.Eat() ‘set Hayop to reference tweety ‘set Hayop to reference tweety Hayop = nemo Hayop = nemo Hayop.Eat() Hayop.Eat() End Sub End Sub End Module End Module ‘set Hayop to reference nemo ‘set Hayop to reference nemo Demonstrating Polymorphic Behavior OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 46
  47. 47. Object-Oriented Programming: Polymorphism Output: Each of these strings is generated by invoking different implementations of the Eat method referenced by the Hayop object variable Demonstrating Polymorphic Behavior OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 47
  48. 48. Object-Oriented Programming: Polymorphism 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 Abstract Classes and Methods OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 48
  49. 49. Object-Oriented Programming: Polymorphism 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: ‘Abstract class Employee ‘Abstract class Employee Public MustInherit Class Employee Public MustInherit Class Employee . . . . . . ' abstract method overridden ' abstract method overridden Public MustOverride Function Public MustOverride Function by derived class by derived class CalculateEarnings() As Decimal CalculateEarnings() As Decimal End Class End Class MustInherit keyword MustOverride keyword A MustOverride procedure doesn’t implement any code Abstract Classes and Methods OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 49
  50. 50. Object-Oriented Programming: Polymorphism 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 NotOverridable Methods and NotInheritable Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 50
  51. 51. Object-Oriented Programming: Polymorphism 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 NotOverridable Methods and NotInheritable Classes OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 51
  52. 52. Object-Oriented Programming: Polymorphism 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 Creating and Using Interfaces OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 52
  53. 53. Object-Oriented Programming: Polymorphism 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 Creating and Using Interfaces OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 53
  54. 54. Object-Oriented Programming: Polymorphism An interface declaration begins with the keyword Interface: Interface keyword ' IPayable interface declaration. ' IPayable interface declaration. Public Interface IPayable Public Interface IPayable Function GetPaymentAmount() As Decimal ' calculate payment Function GetPaymentAmount() As Decimal ' calculate payment Function ToString() As String ' display Payable object Function ToString() As String ' display Payable object End Interface ' IPayable End Interface ' IPayable Interface members will not have any implementation Creating and Using Interfaces OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 54
  55. 55. Object-Oriented Programming: Polymorphism IPayable interface hierarchy <<interface>> <<interface>> IPayable IPayable Invoice Invoice Employee Employee SalariedEmployee SalariedEmployee Creating and Using Interfaces OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 55
  56. 56. Object-Oriented Programming: Polymorphism Using the interface Implements keyword Interface IPayable ' IPayable interface declaration. ' IPayable interface declaration. Public Class Invoice Public Class Invoice Implements IPayable Implements IPayable Public Function GetPaymentAmount() As Decimal _ Public Function GetPaymentAmount() As Decimal _ Implements IPayable.GetPaymentAmount Implements IPayable.GetPaymentAmount ‘implementation here ‘implementation here End Function End Function Public Function ToString1() As String _ Public Function ToString1() As String _ Implements IPayable.ToString Implements IPayable.ToString ‘implementation here ‘implementation here End Function End Function . . . . . . End Class ' Invoice End Class ' Invoice Classes that implements the IPayable should include the methods defined in the interface Creating and Using Interfaces OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 56
  57. 57. Object-Oriented Programming: Polymorphism Exercise OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 57
  58. 58. Object-Oriented Programming: Polymorphism End of Object-Oriented Programming OBJECT-ORIENTED PROGRAMMING Visual Basic 2005 58
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×