CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

48
CSCI 3327 Visual Basic CSCI 3327 Visual Basic Chapter 3: Classes and Chapter 3: Classes and Objects Objects UTPA – Fall 2011

Transcript of CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Page 1: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

CSCI 3327 Visual Basic CSCI 3327 Visual Basic Chapter 3: Classes and ObjectsChapter 3: Classes and Objects

UTPA – Fall 2011

Page 2: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Objectives

• In this chapter, you will– Become aware of reasons for using objects and

classes– Become familiar with classes and objects

2

Page 3: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Introduction

• The book uses car analogy

• We humans are very good in recognizing and working with objects, such as a pen, a dog, or a human being.

• We learned to categorize them in such a way that make sense to us. We may categorize them as animate object, inanimate objects, pets, friends, etc.

3

Page 4: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Introduction (cont'd)

• We some times classify objects based on their attributes, for example, green apples or red apples, fat or slim people, etc.

• If you think about it each object has many attributes. If I ask you list the attributes of an orange, you probably could list many things such as color, shape, weight, smell, etc.

4

Page 5: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Introduction (cont'd)

• In addition to attributes, all objects exhibit behaviors

• A dog eats, barks, wags its tail, plays, and begs. A dog exhibits many more other behaviors than this short list

• Another thing we need to remember about objects is that objects interact between each other

5

Page 6: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Objects

• Objects are packages that contain data and functions (methods) that can be performed on the data.

6

Page 7: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Objects (cont'd)

• Data could be considered to be attributes and functions are considered to be behaviors of the object.

• We can say that the attributes and behaviors are encapsulated into an object.

7

Page 8: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Objects (cont'd)

• The objects interact between each other through their interfaces.

• As an example a date object may have a set of data consisting of month, day and year, and methods consisting of assign date, display date, yesterday and tomorrow.

8

Page 9: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Classes and Objects in Visual Basic

• Classes are types and Objects are instances of the Class.

• Without objects you cannot use a class– Your book says you cannot drive the drawing of a

car

• In Visual Basic, we create a class with the Class statement and end it with End Class

9

Page 10: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

A Class Looks Like This:

Public Class HousePublic Rooms As Integer

End Class

10

Page 11: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Members of a Class

• Fields, Properties, Methods and Events • They can be declared as Public, Private, Protected,

Friend or Protected Friend• Fields and Properties represent information that an

object contains• Fields of a class are like variables and they can be

read or set directly– For example, if you have an object named House, you can

store the numbers of rooms in it in a field named Rooms

11

Page 12: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

The Syntax for a Class

• Public Class Test

'-----Variables'-----Methods'-----Properties'-----Events

End Class

12

Page 13: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Instance Variables (Attributes)

Examples:Amount of gas in your car

Balance in your bank account

13

Page 14: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Using Objects

• Object: car

• Pressing the gas pedal sends a message to the car to perform a task

• Similarly, in programming, you use a method call to send a message to the object

14

Page 15: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Methods (Behavior)

• Methods represent the object’s built-in procedures. 

• For example, a Class named Country may have methods named Area and Population.

15

Page 16: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Defining Methods

• You define methods by adding procedures, Sub routines or functions to your class

• For example, implementation of the Area and Population methods discussed above might look like next slide

16

Page 17: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Example of Defining Methods

Public Class Country

Public Sub Area()Write("--------")

End Sub

Public Sub population()Write("---------")

End Sub

End Class 17

Page 18: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Properties (Attributes)

• Properties are retrieved and set like fields

• If they are public, they can be changed by clients

• Private properties are implemented using Property Get and Property Set procedures which provide more control on how values are set or returned

18

Page 19: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Properties (cont'd)

• Get and set appear to be similar to declaring the properties public

• Through get and set, programmer can have control over setting the properties– For instance, if a client tries to set a date to 37, it

can be checked and set to a default value instead

19

Page 20: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Example GradeBook• Public Class GradeBook• Private courseNameValue As String = "Not set yet"• Public Property CourseName() As String• Get• Return courseNameValue• End Get• Set(ByVal value As String)• courseNameValue = value• End Set• End Property• Public Sub displayMessage()• Console.WriteLine("Welcome to the grade book for " &

vbNewLine & courseName & "!")• End Sub• End Class

20

Page 21: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Example Module• Module GradeBookTest• Sub Main()• Dim theName As String• Dim gradebook As New GradeBook• Console.WriteLine("Initial course name is: " &

gradebook.CourseName & vbNewLine)• Console.WriteLine("Please enter course name: ")• theName = Console.ReadLine()• gradebook.CourseName = theName• Console.WriteLine()• gradebook.displayMessage()

• Console.ReadKey()• End Sub• End Module 21

Page 22: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Events

• We have been programming for events already

• Events allow objects to perform actions whenever a specific occurrence takes place– For example, when we click a button a click event

occurs and we can handle that event in an event handler

22

Page 23: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Creating An Object

• After defining a class, instance of the class, object can be created

• To create a object for this class (Test) we use the new keyword and that looks like this:

• Dim obj As New Test()

23

Page 24: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Sample ProgramImports System.ConsoleModule Module1 Sub Main() Dim obj As New Test obj.disp() Read() End SubEnd Module

Public Class Test Sub disp() 'a method named disp in the class Write("Welcome to OOP") End SubEnd Class 24

Page 25: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Classes

• Constructor

• Destructor

• Properties

• Methods

• Inheritance

• Polymorphism

25

Page 26: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Constructor

• A constructor is a special member function whose task is to initialize the objects of its class

• A constructor is invoked whenever an object of its associated class is created

26

Page 27: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Constructor (cont'd)

• If a class contains a constructor, then an object created by that class will be initialized automatically

• We pass data to the constructor by enclosing it in the parentheses following the class name when creating an object

• In Visual Basic we create constructors by adding a Sub procedure name New to a class

27

Page 28: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Initializing Objects with Constructors in Visual Basic

• The constructor class is called by the class name followed by parenthesis.

• Constructor subroutine can be declared with the "New" keyword.– Public Sub New (ByVal initialBalance As

Decimal)

• Set default value in the constructor– Public Sub New (Optional ByVal initialBalance

As Decimal = 0D)

28

Page 29: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Imports System.ConsoleModule Module2 Sub Main() Dim startObject As New Constructor (10) 'storing a value in the constructor by passing a value(10) WriteLine(startObject.display()) 'calling it with the display method Read() 'reading from keyboard End SubEnd Module

Public Class Constructor Public x As Integer Public Sub New (ByVal value As Integer) 'constructor x = value 'storing the value of x in constructor End Sub Public Function display() As Integer Return x 'returning the stored value End FunctionEnd Class 29

Page 30: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Destructor

• Destructors run when an object is destroyed• Within a destructor we can place code to clean

up the object after it is used• We use "Finalize" method in Visual Basic

– The Finalize method is called automatically when the .NET runtime determines that the object is no longer required

30

Page 31: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Destructor (cont'd)

• When working with destructors we need to use the overrides keyword with Finalize method as we will override the Finalize method built into the Object class

• We normally use Finalize method to deallocate resources and inform other objects that the current object is going to be destroyed

• The following code demonstrates the use of Finalize method

31

Page 32: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Imports System.ConsoleModule Module3 Sub Main() Dim obj As New Destructor End SubEnd Module

Public Class Destructor Protected Overrides Sub Finalize() Write(“Destroyed!") Read() End SubEnd Class

32

Page 33: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Property Values

• Get and Set

• Get allows you read the current property value

• Set allows you to change the property value

• Property without a "ReadOnly" or "WriteOnly" specifier must provide both a "Get" and a "Set"

33

Page 34: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Modules, Classes and Methods

• Both classes and modules contain methods (Subs)

• Related classes are grouped into namespaces and compiled into library files

• A module contains declarations and procedures that are used by other files in a project– Module is not associated with a class or form and

contain no event procedures

– Good to use in case you are using multiple forms

34

Page 35: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Private and Public in a Module

• Private – procedures and variables declared as private can only be accessed by statements in the same module

• Public – accessible by statements either inside or outside the module

• By default, Sub declarations are Public

• Variables declared with Dim or Private – variables are private

35

Page 36: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Inheritance

• A key feature of OOP is reusability

• It's always time saving

• It can be used by other programs to suit the program's requirement

• This is done by creating a new class from an existing class

• The process of deriving a new class from an existing class is called Inheritance

36

Page 37: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Inheritance (cont'd)

• The old class is called the base class

• The new class is called derived class

• The derived class inherits some or everything of the base class

• In Visual Basic we use the Inherits keyword to inherit one class from another

37

Page 38: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Inheritance (cont'd)

• New class is created from an existing one by adding new or modified capabilities

• The new class is a derived class or subclass – A derived class can become a base class for a

future derived class

• Is-a relationship – represents inheritance– A car is a vehicle

• Has-a relationship – represents a composition – A car has a steering wheel

38

Page 39: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Inheritance Coding

Public Class One------End Class

Public Class Two     Inherits One------End Class

39

Page 40: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Inheritance Coding (cont'd)

Imports System.ConsoleModule Module4

Sub Main() Dim ss As New Two WriteLine(ss.sum()) Read() End Sub

End Module

(see next slide for inheritance)

40

Page 41: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Public Class One Public i As Integer = 10 Public j As Integer = 20 Public Function add() As Integer Return i + j End FunctionEnd Class

Public Class Two Inherits One Public k As Integer = 100 Public Function sum() As Integer 'using the variables, function from base class and adding more functionality

Return i + j + k 'Return add() +k End FunctionEnd Class 41

Page 42: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Protected Members

• Public and Private• In the base class, private members are not

inherited by derived classes• Protected access offers an intermediate level of

access between Public and Private. – A base class’s protected members can be accessed

only by members of that base class and by members of its derived classes

42

Page 43: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Friend Members

• Friend access is another intermediate level access

• If a program uses multiple classes from the same assembly, these classes can access each other’s friend members

• Unlike public access, programs that are declared outside the assembly cannot access these Friend Members

43

Page 44: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Example of Friend Members in Visual Basic

44

Page 45: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Polymorphism

• It means "one name, multiple forms"

45

Page 46: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Example of Polymorphism

• Suppose there is a base class called Animal with a method called move

• There are three derived classes called fish, frog and bird

• Program calls move to all three objects of the derived class– Fish swims, frog jumps, and birds fly – This is possible because of polymorphism

46

Page 47: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Polymorphism Analogy

• If you are asked to open, you will know what to do depending on what the object you are working with: a door, a jar, an envelope, etc.

47

Page 48: CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.

Abstract and Concrete Classes

• Abstract Classes that are not used to make objects

• Abstract classes are incomplete and are used only as base classes to make derived classes

• Derived classes that can be used to instantiate objects are called concrete classes

48