Title: Advanced Interactive Programming Object Oriented Programming OOP Objects and Classes
1Advanced Interactive ProgrammingObject Oriented
Programming (OOP)- Objects and Classes -
2Outline
- Concepts and terminology
- Object properties, methods and events
- Class instance
- Message
- Information hiding
- Encapsulation
- Data abstraction
- Object oriented programming paradigm
- OOP in VB
- Create and manipulate classes, objects, methods
and properties
3Objects
- Originated from real world observation - an
object is a dog, a car or a chair, a desk, etc. - In theory, we should be able to describe all of
our experience and surroundings as objects - All objects have attributes and behaviors
4Attributes
- Attributes are characteristics
- Use attributes to describe the states and
appearance of an object - Appearance may include size, shape and color
- States may include temperature, speed, on/off,
etc. - For example - a car is in Red with engine size
1.1 made by Ford these characteristics represent
values assigned to attributes
5Behaviors
- Behaviors are actions
- Use behaviors to describe the active behavior
of an object - Example - a car, an automatic door, a mobile
phone - These behaviors become evident if a specific
action of the object is activated
6Software Objects
- Modelled after real-world objects in that they
too have state and behavior - In OOP, an object is a structure that contains
both data and methods that manipulate that data - The data represent the attributes of the object
- An object is responsible for its own data
- An object is active, not passive it does things
- The methods implement the behaviors
- An object can expose data and methods to other
objects
7Classes
- Originated from real world observation many
objects are of the same kind - A class is a blueprint, a type or say a pattern,
which defines the implementation of a particular
kind of object. - You might think of a class as a cookie cutter and
a set of objects as cookies created with that
cutter (class)
Class
Object
8A Conceptual View about Classes
- Classes describe the common characteristics of
the same kind of objects. These include - The attributes, represented by variables
- The behaviors, represented by methods
- The interface - how other objects access these
variables and/or methods such as the front panel
of a washing machine, a microwave, or the remote
control of a TV - The events
9A Practical View about Classes
- In practice, a class is a unit or module of code
that may be used to define the attributes and
behaviors of a kind of object - The commonly used functions have all been
implemented in software and further packaged as
classes. Classes pre-exist and are stored in
special files called libraries - Application programmers only need to write
application specific classes also referred to
as programmer-defined types
10Objects versus Classes
- A class is a data type or blueprint or template,
not an object itself. For example a blueprint of
a car is not a car - An object is a concrete, particular entity, which
is generated by instantiating a class - An object is an instance of a class
- An object has all the attributes, behaviours,
interfaces and events defined by the class
11Example A Time Class and Object
- You could create a class representing time
- It would have attribute data
- Hour, minute and second
- And methods
- Set time to a specific time
- Convert time to standard time
- Convert time to universal time
- Many time objects - a real world clock, watch,
timer in microwave, ant real time control systems
12Example Code
13Information Hiding
- A principle for the hiding of design decisions
(implementation details) in a computer program
that are most likely to change - A means to protect other parts of a program from
change if the design decisions are changed - A program needs to provide a stable interface
which shields the implementation details from how
the program is interacted by other programs - Many ways encapsulation and polymorphism
14Encapsulation
- A technique for wrapping up data and associated
behaviors into a single unit or object, e.g. a
class - Provide controlled interface (namely, the class's
public methods) to manipulate an objects data - Support information hiding the interfaces
specify how a program may use the object but
hiding the implementation details. - It is not necessary for a programmer who uses a
pre-existing class to know or understand its code
structure
15Data Abstraction
- A mechanism or practice to describe and model
data types, e.g. classes, in terms of behaviours
without concern for how those behaviours are
actually implemented - It enforces a clear separation between the
abstract properties of a data type and the
concrete details of its implementation - The abstract properties are those that are
visible to client code, i.e. the interface, while
the concrete implementation is kept entirely
private, which has no impact on the interface - Data abstraction leads to inheritance and
polymorphism
16Messages
- A single object will not do much, therefore not
useful - Objects interact with each other by sending
messages - A message is information which is sent from a
source to a receiver - Message content
The object to which the message is addressed
(YourCar) The name of the method to perform
(changeGears) Any parameters needed by the
method (secondGear)
17CTime Class Revisited
18A Class Interface CTime Class
- The implementation code of a class is
encapsulated - Attributes appear at the interface of the class
as properties - Actions appear at the interface of the class as
methods
19Access to Properties and Methods
- Only public variables and methods are accessible
- Programmers use dot notation to gain access to
properties and methods - To assign a value to a property of an object
object.property value - To run a method of an object object.method
20Differences between Objects and Classes
Properties and Methods
- Class variables vs. instance variables
- A class variable contains information that is
shared by all instances of the class - A instance variable contains information for the
particular object - Class methods vs. instance methods
- A class method is invoked without reference to a
particular object. Class methods affect the class
as a whole, not a particular instance of the
class - A instance method is invoked with reference to a
particular object. It inspects or changes the
state of a particular object - VB does not distinguish this
21Object-Oriented Programming
- OOP is a programming paradigm, i.e. a style of
programming - Building blocks (Unit of abstraction) are
classes, objects - Each object is capable of receiving messages,
processing data, and sending messages to other
objects - A computer program is composed of a collection of
structured objects
22Object-Oriented Programming
- Programming in object-oriented languages is
called object-oriented programming, C, C,
JAVA, etc. - VB is an object-oriented programming language
- Beware VB ?OOP, OOD ? OOP and VB is not a pure
OOP language - Important objects and classes (properties,
methods, and events) are only one half of the
object-oriented programming equation. True
object-orient programming requires objects to
support three qualities encapsulation,
inheritance, and polymorphism.
23Why Objects-oriented
- Object-oriented programming models the world as a
collection of objects - Intuitive, since this is how we tend to think in
terms of the world (e.g., people, animals, cars,
etc.) - And how we construct real world artefacts, cars,
houses, etc. - Complex problems can be solved by Divide and
conquer approach - Enhance reusability, maintenance and flexibility
you only write a very small portion of the code
for your application, most code is from reusable
objects in library
24Approximate Terminology
- class user defined type an abstract data type
- object instance (of a class)
- state attribute property
- field variable
- method function
- behaviour operation action
- sending a message to an object calling a method
- These are all approximately true
25Creating Classes in VB
- Properties, Methods and Events
26Creating a Class
- Use class module similar to adding a form or a
standard code module - The name represents the class
- Only code, no GUI
- Code in class module contains the encapsulated
description of the class i.e. properties,
methods and events
27Example A CTime Class
- We will construct a time class CTime2 that we
mentioned before - When completed, an object of CTime2 will be able
to show various behavior of time - Set the time
- Increase time by a second a time
- Increase a minute every 60 seconds and a hour
every 60 minutes - Display the time in universal format or standard
format
28Class Properties
- Properties refer to attributes that hold data
that describe an object - Attributes are declared as variables for the
class module
29Example
Class CEmployee
Attributes gt Variables
- They are called module-level variables before
- In OOP, variables within a class are called
instance variables
30Member Access Control
- Class members include variables and methods
- Member access specifiers include keywords
- Public accessible to all modules within the
project - Private accessible only to methods of the class
31Example Code Access Control
Private instance variables can only be
manipulated by methods of the class
Public instance variables and Public methods are
accessible to every module within a project
Private methods can only be called by other
methods of the class utility or helper methods
32Example Access Errors
33Property Procedures
- Property Procedures refer to procedures that read
and assign new values to private variables from
outside the object - These Property Procedures and the instance
variables they manipulate collectively are called
propeties - A layer of indirection facilitates
- Validation checking
- Translation and transformation of interface data
forms and implementation data
34Manipulating a Class Property
- Property Get procedure (accessor or query method)
- Obtain the values of private instance variables
- Property Let/Set procedure (mutator method)
- Control the setting of instance variables to
valid values - Let procedure for normal instance variables
- Set procedure for object variables
- Get and Set or Let are not always required
- A property with only Get procedures is called
ReadOnly - A property with only Let/Set procedure is called
WriteOnly
35Example Code
36Creating Class Methods
- Operations on class data are coded and placed in
functions or procedures within the class - We call these procedures methods
- Scope procedures in terms of access control into
private and public - Public methods form part interface of a class,
through which data can be manipulated
37Method Overloading
- A class method can have several signatures
- Each signature provides a different version of
the method, which have the same name, but accept
different number of arguments, or arguments with
different data types. - Not supported in VB 6
Public Function Addition(num1 As Integer, num2 As
Integer) As Integer Addition num1 num2 End
Function
Public Function Addition(num1 As Integer, s As
String, num2 As Integer) As Integer Addition
num18 (num2 3) CInt(s) End Function
38Example Methods in Object Browser
39Object Variables
40Use of Objects and Classes
- Classes are seldom used directly except they have
class variables and methods - Use classes to create objects
- Use objects to build applications
- For example, all components in a form are objects
41Object Variables
- Object variables are used to refer to objects
- Declare object variables similarly to numeric or
string variables - For example, int n does two things
- it declares that n is an integer variable
- it allocates space to hold a value for n
- Object variables are references or pointers to
objects and do not contain the objects.
42Declare and Create Objects
- Private mTime As CTime2 // does one thing, it
declares that mTime is of type CTime2 - The Set statement is used to associate objects
with variable names - Set mTime New CTime2 // allocates space
associating a object variable to an instance - We say Set binds the object to the variable
name - Keyword New instantiates an object of a specified
type
43Equivalent Statements
- Either of these statement options may be used to
instantiate a new object and associate it with a
variable - Dim mTime As New CTime2
- OR
- Dim mTime As CTime2
- Set mTime New CTime2
- But the mTime object is still "blank, only a
placeholder in memory - mTime.Hour txtHour.Text // dot notation
- mTime.Minute txtMinute.Text // assignment via
Let property procedure - In VB an object is not created until the first
time a property or method of the object is called
44CTime2 Class Demo
45Classes and Events
- A class has only two built-in events, i.e.
Initialize and Terminate - A class can raise user-defined events declared in
the class - Purpose is to notify other objects that something
happened
46The Initialize Event
- Assign default values to class properties at
instantiation - Initialize event fires every time an instance of
a class is created, including built-in classes
such as Forms - The Initialize event occurs before the Load event
- The event is raised once in an objects lifetime
- The event method is Class_Initialize()
47The Terminate Event
- Used to clean up an object before the object is
destroyed - Fires when the last reference to the class
instance is removed from memory - Set to a different object
- Set to Nothing
- Largely related to memory management, releasing
memory - Occurs after the Unload event for all objects
- The event method is Class_Terminate()
48Raising an Event in a Class
- An user-defined event must be declared in the
classs general declaration - Use Event keyword
- Must be declared as Public
- Event parameters are used to pass data to and
receive data from the program - Use RaiseEvent statement to raise an event
49Example Code
50React to Events in a Program
- A program (a form or separate class) that use the
event class defines how to react to the events - When an event is raised the object broadcasts a
stimulus throughout the system - Event handlers are procedures that execute when
they detect a specific event stimulus
51Demo
52Reference a Field or Method
- Inside a class, no dots are necessary, use them
directly - Outside a class, you need to say which object you
are talking to - If mTime.Second 0 Then
- mTime.Minute (mTime.Minute 1) Mod 60
- If you don't have an object, you cannot use its
fields or methods!
53Changing Properties of Instances
- Properties of an object may be changed at run time
54Objects Reuse
- Composition or aggregation building new classes
from objects of existing classes - Use references to refer to existing objects
- A class can have multiple instances
simultaneously -
-
55Example a CDate1 Class
Declares three integers mMonth, mDay, and mYear
Assigns values to class variables mMonth, mDay,
mYear after error checking
56Example an CEmployee Class
Declares two Private strings and two Private
object references
Class CEmployee references to objects of class
CDate1, mBirthDate and mHireDate
57Example an Employee Class
- In the CEmployee class, two CDate1 objects are
referenced (used) - Objects can be used as arguments and passed among
objects
CDate1 objects are passed to procedures to
create HireDate and BirthDate
58Classes vs Objects in VB IDE
- The controls on the Toolbox in Visual Basic
represent classes. When you drag a control from
the Toolbox onto a form, you are creating an
object an instance of a class - The form you work with at design time is a class.
At run time, Visual Basic creates an instance of
the form's class that is, an object
59Classes in VB IDE
- Visual Basic is totally object-oriented
- Object Browser
- Lists the Framework Class Library available in
Visual Basic - Or classes in specific packages
60OOP in VB
- You have already used OOP in VB but only with
built-in classes - All the forms and controls we have used so far
are objects arising from classes - When you add a control to a form the control is
already programmed for the events it will raise - All VB objects (controls and forms) support the
concept of encapsulation and information hiding
implementation details are unseen to programmers
61Objects as Control (class) Instances
62Forms as Classes
- Designing a form is really the creation of a new
class. This is different from other controls - Individual forms are instantiated when you use
the New keyword - The form exists as an object, but it has no
window. None of its controls exist yet before
Load statement
63Example Multiple Instances of a Form
- Properties of a new instance may be changed at
run time
64Creating OO Applications
- Design and write your own classes based on the
business logic of your application - Use as many pre-existing classes as possible
- Implement the application by aggregation and
composition of your own classes and existing
classes
65Good Programming Practice
- Data members should almost always be scoped
private to the class module - Use a consistent naming convention for class data
members - Initialize all data members with default values
- Make code robust and reusable
66Summary
- Object thinks concepts
- Object speaks terminology
- OOP in VB