4. Objects in Visual Basic .NET Creating new data types Overview - - PowerPoint PPT Presentation

4 objects in visual basic net
SMART_READER_LITE
LIVE PREVIEW

4. Objects in Visual Basic .NET Creating new data types Overview - - PowerPoint PPT Presentation

4. Objects in Visual Basic .NET Creating new data types Overview Creating and destroying objects Encapsulation Methods and Properties Constructors Conditional execution and events Variables value and reference objects


slide-1
SLIDE 1
  • 4. Objects in Visual

Basic .NET

Creating new data types

slide-2
SLIDE 2

Overview

Creating and destroying objects Encapsulation Methods and Properties Constructors Conditional execution and events Variables – value and reference objects

slide-3
SLIDE 3

Classes

A Class is a template for creating objects

Create one class, get many objects Class allows definition of composition (what data it

will contain) and behaviour (what operations it will support) of an object

Class Objects are different from simple variables

(Value Objects)

Need to be explicitly created and assigned to an

  • bject variable (using the New keyword)

Can be destroyed (removed from memory) This distinction makes Class Objects (also known as

Reference Objects) slightly more awkward to deal with, but much more efficient

slide-4
SLIDE 4

Creating and destroying reference (class) objects

Sub Main() Dim MyAccount As BankAccount = New BankAccount() MyAccount.Deposit(100.00) MyAccount.Withdraw(20.00) Console.WriteLine(“Balance is £{0}”, MyAccount.GetBalance( )) MyAccount = Nothing End Sub BankAccount

  • bject created here

BankAccount object destroyed here (this will also happen automatically if the statement is missed out)

slide-5
SLIDE 5

Encapsulation

Recall that Encapsulation is a

key feature of object-oriented programming

i.e. Creating capsules of code

that provide controlled ways of accessing their internal data

Encapsulation can be created

using the keywords Private (for restricted access) and Public (for complete access) as tags on variable, class and member (of class) definitions

Typically, Private is used to

deny access to member variables

Public Class BankAccount Public AccountName As String Private Balance As Integer End Class This can be accessed directly by code that uses the object This can’t

slide-6
SLIDE 6

Class Methods

Methods are operations defined for a class

Usually to alter the value of one or more member

variables, or to retrieve some information from them

A method can be a Sub or a Function

A Sub performs some operation on the object A Function returns a value derived from the data in

the object’s member variables

Methods are Public, and so can be accessed by

code that uses an object of the class

Allows data in Private member variables to be

accessed

slide-7
SLIDE 7

A Class

Member variables

(AccountName and Balance) store data

Methods (Deposit and

GetBalance) manipulate the member variables or retrieve data from them

Public items can be

accessed by code

  • utwith the class

Private items can only

be accessed by methods of the class

Public Class BankAccount Public AccountName As String Private Balance As Decimal Public Sub Deposit(ByVal Amount As Decimal) Balance += Amount End Sub Public Function GetBalance() As Decimal Return Balance End Function End Class

slide-8
SLIDE 8

Properties

A Property is a value that is part of an object and

made accessible by it

Two ways of creating a property

A Public member variable A Public Property definition

This is a special type of code routine that provides read

and/or write access to values derived from member variables, either public or private ones

Defining a Property for a class gives us a way of

restricting access to internal data in whatever way we want

slide-9
SLIDE 9

Example Properties

Class Circle Public Radius As Single Public Property Diameter As Single Get Return 2 * Radius End Get Set(ByVal Value As Single) Radius = Value / 2 End Set End Class Sub Main() Dim C As New Circle C.Radius = 10 Console.WriteLine(C.Diameter) C.Diameter = 5 Console.WriteLine(C.Radius) End Sub Radius a public member variable, and behaves as a Property

  • f the class

Diameter is a Property definition, whose value is determined by program code. Get part determines value when the property is ‘read’, Set part defines how to update the property value.

slide-10
SLIDE 10

Using a property to restrict access

A ReadOnly property has only a Get part, so

  • nly allows a value to be retrieved from an
  • bject

A WriteOnly property has only a Set part, so only

allows a value to be assigned (this is more unusual)

Class BankAccount ‘ ‘ ‘ ‘ ‘ Public ReadOnly Property CurrentBalance() As Decimal Get Return Balance End Get End Property End Class

slide-11
SLIDE 11

Constructors

A new member of a class will initially have all member

variables set to zero (0, “”, 0.0, False etc.)

This may be invalid for some objects

e.g. a Circle or radius 0 is not a circle

A Constructor method is a special purpose Sub that is

defined to set the initial state of an object when it is created

A Constructor is always called Sub New(), but several

versions can be created in which different combinations

  • f data can be used to set the initial state
slide-12
SLIDE 12

Example Constructors

Public Class BankAccount Public AccountName As String Private Balance As Decimal Public Sub New(ByVal Name As String) AccountName = Name End Sub ‘ ‘ ‘ ‘ ‘ End Class Public Class Circle Public Radius As Single Public Sub New(ByVal InitialRadius As Single) 'This method executes at the point where New is used to 'create a Circle (InitialRadius is the Parameter)... Radius = InitialRadius End Sub ‘ ‘ ‘ ‘ ‘ End Class

slide-13
SLIDE 13

Overloaded Constructors

It is possible to define more than one constructor

for a class

Versions must differ in number or types of parameters

(initial values) passed in

Public Class BankAccount ‘ ‘ ‘ ‘ ‘ Public Sub New(ByVal Name As String) AccountName = Name End Sub Public Sub New(ByVal Name As String, ByVal Initial As Decimal) AccountName = Name Balance = Initial End Sub ‘ ‘ ‘ ‘ ‘ End Class Dim MyAccount As BankAccount _ = New BankAccount(“Fred Bloggs”) Dim MyAccount As BankAccount _ = New BankAccount(“Fred Bloggs”, 100)

slide-14
SLIDE 14

Conditional execution

It is useful to have certain operations organised so that

they will only execute if the conditions are appropriate

Apply discount IF a customer has spent more than £50 Accept a job applicant IF the person has a programming

qualification

This is the key feature that makes computer programs

more than simple calculations

A program can behave in a way that adapts to circumstances

In a class, we can use this to make any or all of the

methods more ‘intelligent’

slide-15
SLIDE 15

Example conditional code

Public Class BankAccount ‘ ‘ ‘ ‘ Public Sub Withdraw(ByVal Amount As Decimal) If Amount <= Balance Then Balance -= Amount End If End Sub End Class

Withdrawal is only allowed if there is enough cash in the account to cover it.

slide-16
SLIDE 16

Events

An event is a signal from an object that

something significant has happened

Someone just clicked on a button with the mouse The last number in a list has been processed A BankAccount has gone overdrawn

We can define a new type of event to suit

whatever circumstances it would be worth responding to

Unlike an If..Then statement that will always respond

by executing the code defined within it, an event can be ignored, or a programmer can decide later how to react to it

slide-17
SLIDE 17

Example Event

Class BankAccount Public Event Overdrawn(ByVal Amount As Decimal) ‘ ‘ ‘ ‘ ‘ Public Function Withdraw(ByVal Amount As Decimal) mvarBalance -= Amount If Balance < 0 Then RaiseEvent Overdrawn(mvarBalance) End If End Function End Class Sub Main() Dim A As BankAccount = New BankAccount ‘ ‘ ‘ A.Withdraw(200) End Sub Private WithEvents Account As BankAccount 'Other code... Sub DealWithOverdraft(ByVal Amount As Decimal) _ Handles Account.Overdrawn Console.WriteLine("Account is overdrawn by : {0}", Amount) End Sub Event is defined in the class, and raised in any section of code that you decide should cause it. 1 An event handler is defined in a program to indicate how the event should be dealt with 2 The event is raised automatically if the circumstances defined for the event occur 3

slide-18
SLIDE 18

Variables

In Visual Basic .NET, every variable is an object, but

there are two types:

Value objects (or value types) Reference objects (or reference types)

A Value object exists as soon as it is declared (with a

Dim…, Private… or Public… statement)

It will immediately be given a zero value unless it is initialized

A Reference object must be created with the New

keyword – until then, it is Nothing

Until New is used, there is no object and an attempt to access

any of its Properties or Methods will cause a crash

slide-19
SLIDE 19

Value and Reference objects

Sub Main() Dim i As Integer Dim a As BankAccount a = New BankAccount ‘ . . . End Sub

Nothing BankAccount Object

slide-20
SLIDE 20

Differences between value and reference objects

A value type variable stores the value A reference type variable is a reference to an object, or

Nothing

Copy a value type, create a second copy Copy a reference type, create a second reference to the

same object

After the last statement in a block (e.g. a Sub) is

executed, value types declared within it disappear

Objects referred to by reference variables declared

within a block can continue to exist provided some reference variable outside the block is made to refer to the object

slide-21
SLIDE 21

Distinguishing between value and reference types

The types are simple to recognise Simple variables are value types

Numbers, dates, characters (char), Booleans,

structures, enumerations

All Classes and Strings are reference types

In some cases, strings behave like value types, since

they can be copied – this is a deliberate feature

slide-22
SLIDE 22

Summary

A class is a definition for a type of object Class objects need to be created and can be destroyed Public and Private can be used to define how a class is

encapsulated

Properties and Methods define the content and

behaviour of all of the objects in a class

Constructors are used to put an object into a well defined

state

Conditions can be used to control what code is executed

and to generate events

There are two types of variable – value and reference

  • types. There are differences in how these are created,

copied and destroyed