Object-Oriented Programming: Classes and Objects

Download Report

Transcript Object-Oriented Programming: Classes and Objects

Object-Oriented Programming: Classes and Objects

Multitier Applications

• Classes are used to create multitier applications.

• Each of the functions of a multitier application can be coded in a separate component and stored and run on different machines.

• Goal is to create components that can be combined and replaced.

Three-tier Model

• Most popular implementation

"Cookie Analogy"

• Class = Cookie cutter • Instantiate = Making a cookie using the cookie cutter • Instance = Newly made cookie • Properties of the Instance may have different values.

• Icing property can be True or False.

• Flavor property could be Lemon or Chocolate • Methods = Eat, Bake, or Crumble • Events = Cookie crumbling and informing you

Object-Oriented Terminology

Encapsulation

Inheritance

Polymorphism

Encapsulation

• Combination of characteristics of an object along with its behavior in "one package" • Cannot make object do anything it does not already "know" how to do.

• Cannot make up new properties, methods, or events.

• Sometimes referred to as data hiding, an object can expose only those data elements and procedures that it wishes.

Inheritance (1 of 2)

• Ability to create a new class from an existing class • Original class is called Base Class , Superclass , or Parent Class.

• Inherited class is called Subclass , Derived Class , or Child Class.

• For example, each form created is inherited from the existing Form class.

• Purpose of inheritance is reusability.

Inheritance Example

• Base/Parent Class • Person • Derived/Child Class • Employee • Customer • Student The derived classes inherit from the base class.

Polymorphism

• Methods having identical names, but different implementations • Radio button, check boxes, and list boxes all have a Select method—the Select method operates appropriately for its class.

• Overloading • — Several argument lists for calling the method Example: MessageBox.Show method • Overriding — Refers to a method that has the same name as its base class • Method in subclass takes precedence.

Designing Your Own Class

• Analyze characteristics needed by new objects.

• Characteristics or properties are defined as variables.

• Define the properties as variables in the class module.

• Analyze behaviors needed by new objects.

• Behaviors are methods.

• Define the methods as sub procedures or functions.

Creating Properties in a Class

• Define variables inside the Class module by declaring them as Private — these store the value of the properties of the class.

• Do not make Public, since that would violate encapsulation (each object should be in charge of its own data).

Property Procedures

• Properties in a class are accessed with accessor methods in a property procedure.

• Name used for property procedure is the name of the property seen by the outside world.

• Set accessor method.

• Uses Value keyword • to refer to incoming value for property Assigns a value to the property • Get Statement uses the value keyword to refer to the incoming value of the property.

• Must assign a return value to the procedure name or use a Return Statement to return a value.

Property Procedure General Form

{Private | Protected }

ClassVariable

As

DataType

[Public]

Get Property

PropertyName( )

As

DataType Return ClassVariable [|PropertyName = ClassVariable]

End Get Set

(ByVal Value As

DataType

) [

statements, such As validation

]

ClassVariable

= Value

End Set End Property

Read-Only Properties

• In some instances, a value for a property can be retrieved by an object but not changed.

• A property can be written to create a read-only property.

• Create a read-only property by using the ReadOnly modifier.

' The property procedure for a read-only property.

ReadOnly Property TotalPay() As Decimal Get Return TotalPayDecimal End Get End Property

Write-Only Properties

At times, a property can be assigned by an object, but not retrieved.

• Create a property block that contains only a Set to create a write-only property.

' Private module-level variable to hold the property value.

Private PriceDecimal As Decimal Public WriteOnly Property Price() As Decimal Set(ByVal value As Decimal) If value >= 0 Then PriceDecimal = value End If End Set End Property

Constructors and Destructors

• Constructor • Method that automatically executes when an object is instantiated • Constructor must be public and is named New.

• Ideal location for an initialization tasks such as setting the initial values of variable and properties • Destructor • Method that automatically executes when an object is destroyed • Rarely needed in .NET classes (automatic garbage collection)

Overloading the Constructor

• Overloading means that two methods have the same name but a different list of arguments (the signature).

• Create by giving the same name to multiple procedures in a class module, each with a different argument list.

Parameterized Constructor

• Constructor that requires arguments • Allows arguments to be passed when creating an object

Value Types and Reference Types

Data types are divided into two categories— value types types .

and reference A variable of a value type (such as Integer ) contains a single value of that type

.

Dim CountInteger as Integer = 7 A reference type variable is initialized by default to the value Nothing if you do not initialize it in its declaration to refer to an object.

When you attempt to use a variable that contains Nothing to interact with an object, you’ll receive a NullReferenceException .

Dim Employee as Person

Class Scope

A class’s instance variables, properties and methods have class scope .

Within this scope, a class’s members are accessible to all of the class’s other members and can be referenced simply by name.

Outside a class’s scope, class members cannot be referenced directly by name.

Those class members that are visible (such as object of the class (for example, time.Hour

Public members) can be accessed through a variable that refers to an ).

Object Initializers

Object initializers use the With keyword to allow you to create an object and initialize its properties in the same statement.

This is useful when a class does not provide an appropriate constructor to meet your needs.

To use object initializers, you follow the object creation expression with the With keyword and an object initializer list —a comma-separated list in curly braces ({ }) of properties and their values as in the following statements: Dim timeObject1 As New Time() With {.Minute = 33 , .Second = 12 } Dim timeObject2 As New Time() With {.Minute = 45 } Each property name must be preceded by the dot separator (.) and can appear only

once

in the object-initializer list.

Auto-Implemented Properties

For properties that do not have any additional logic in their Set and Get accessors, there’s a feature—called code for you.

auto-implemented properties —that allows you to write one line of code and have the compiler to generate the property’s Public Property Hour As Integer The compiler would then generate a Private instance variable of type Integer named _Hour and the following property code Public Property Get Return Hour _Hour As Integer End Get Set (value As Integer ) _Hour = value End Set End Property

Using

Me

Object to Access the Current

Every object can

access itself

through its Me reference .

Public Sub New (hour As Integer , minute As Integer , second As Integer ) Me .hour = hour ' initialize instance variable hour Me .minute = minute ' initialize instance variable minute Me .second = second ' initialize instance variable second End Sub ' New The identifiers qualified with “ Me.

” represent the instance variables.

The unqualified identifiers represent the constructor’s parameters.

Garbage Collection

Every object you create uses various system resources, including the memory that holds the object itself.

These resources must be returned to the system when they’re no longer needed to avoid resource leaks .

The Common Language Runtime (CLR) performs automatic garbage collection to reclaim the memory occupied by objects that are no longer in use.

When there are no more references to an object, it’s marked for garbage collection by the CLR.

Garbage Collection

Resources like memory that are allocated and reclaimed by the CLR are known as managed resources .

Other types of resource leaks can occur.

◦ For example, an app may open a file on disk to modify the file’s contents.

◦ If the app does

not

close the file, other apps may not be allowed to use the file until the app that opened the file finishes.

Resources like files that

you

resources must manage are known as unmanaged (because they’re not managed by the CLR).

◦ Such resources are typically scarce and should be released as soon as they’re no longer needed by a program.

Instance Variables versus Shared Variables

• Instance variables or properties • Separate memory location for each instance of the object • Shared variables or properties • Single variable that is available for ALL objects of a class • Can be accessed without instantiating an object of the class • When creating, use the Shared keyword to create.

• Shared properties can be set to read-only so that their values can be retrieved but not set directly.