introduction to object-oriented programming · what is object oriented design, programming, and...

Post on 15-Jul-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Andreas SavvaUniversity of Cyprus

24 January 2008

Introduction to Object- Oriented Programming

What is Object Oriented

Design, programming, and languagesAn alternative to procedural programming

anything done using O-O can also be done using a procedural paradigm

Considering a problem from the perspective of objects and how they interact

Skills for Object Oriented programming

Understanding of subprograms and parameters

stepwise refinementShould understand references/pointersCoding still involves basic concepts

selection structures, repetition structures, …

Object Oriented vs. Procedural

Procedural ParadigmProgram defines data and then calls subprogram to act on the data

Object ParadigmProgram creates objects that encapsulatethe data and procedures that operate on the data

Top down vs. Object Oriented

Top-down structured design: uses algorithmic decomposition where each module denotes a major step in some overall process

Object-oriented design: divides the problem into a set of objects that interacts to solve the problem. Your program’s properties and behaviors are modelled based upon real objects like cars, books, houses, etc.

Why Object OrientedSoftware is complex (too many people is doing too many things – the mess is inevitable ☺ )

One of the main goals in programming is to avoid the redundancy and objects can help to do this (inheritance)

Objects can help increase modularity through data hiding (encapsulation)

Basic Concepts of Object OrientedObjects

Hidden data that is accessed and manipulated through a well-defined interface

ClassesA template or “blueprint” for creating objects, each with their own data

InheritanceA new class created by modification of an existing class

ObjectsPart of a program which

models some real or conceptual objecthas behaviouralresponsibilities (behaviours)has informational responsibilities (attributes)

Behaviours (methods)things an object can “do”like procedures and functions in other languages

Attributes (fields)information an object “knows” (has-a)like data and variables in other languages (records)

ClassesA class is a template. No data is allocated until an object is created from the class. However attributes and behaviours are generically defined

The creation (construction) of an object is called instantiation. The created object is often called an instance (or an instance of class X)

Objects and Classes

An object is an instance of a class.

If we have a class definition called Car, then we can think of Audi, BMW, and Corvette as each being an instance (object) of the class Car, i.e., they are each a type of car.

ClassesOnce a class is defined you can create as many instances of the class (objects from the class) as you would like.Once a blue print is completed for the 2003 Porsche 911, Porsche will use an assembly line to build as many instances of the 2003 Porsche 911 as they wish.

Class car and objects- graphically

Audi 6 BMW Z3 Corvette

Car Car Car

CarThis line shows an

instance-of relationship.

Defining a classProperties are variables which describe the essential characteristics of an object.• Properties of a car: color, model, make,

how many doors, transmission type, direction of movement, etc.

Behaviors are methods that describe how the object behaves and how the properties may be modified. • Behavior of a car: braking, changing gears,

opening doors, moving forwards or backwards, etc.

Defining a class

Behavior or Method 1

Behavior Behavior or or

Method 4 Method 2

Behavior or Method 3

Properties

or

Instance Variables

Instance variablesThe class definition will include parameter definitions (properties) that represent data about a particular object, instance variables.

Example, Jessica's car may have 4 gallons of gas in it while Clint's car has 10 gallons.

• The amount of gas in each car may change without affecting the amount of gas in the any other cars.

• All instances (objects) of a class will have a set of instance variables that are specific to that individual object.

• The combination of the values of these instance variables is known as the object’s state.

Instance variables

Audi 6 BMW Z3 CorvetteCar Car Car

Car

MaxSpeed = 155 MaxSpeed = 165 MaxSpeed = 145

MaxSpeed

Class variablesThe class definitions may also include parameter definitions that represent data that is shared by all class instances (objects), called class variables.

In the case of the car class, we will define a maximum allowed speed, by the law (variable LMaxSpeed). This will be the same for each individual car (that’s why your car have those annoying speed limiters ☺).

Class variables

Audi 6 BMW Z3 CorvetteCar Car Car

Car

MaxSpeed = 155 MaxSpeed = 165 MaxSpeed = 145

MaxSpeed

LMaxSpeed=155

Class variables

Class variables may also be used to keep track of things such as how many instances of a class exist.

Example: let’s create a counter the records how many cars are in the garage.

Class variables

Audi 6 BMW Z3 CorvetteCar Car Car

Car

MaxSpeed = 155 MaxSpeed = 165 MaxSpeed = 145

MaxSpeed

LMaxSpeed=155

NumCars = 3

Constant parametersIf it was variables instead of parameters, that would be oxymoron.

If there is a parameter whose value should not change while your program is running, that parameter type is called a constant.

The LMaxSpeed parameter that we defined for the Car class is a constant. The maximal speed is limited by the low, and it cannot be changed once the car has been built.

Messages

For Objects

The object to whom the message is being sent.

• The name of the method (behavior) that object is to execute.

• Any parameters (variables) needed by that method.

For Humans

Who the message is for.

What we want the person to do.

• What information is needed to do it.

Audi 6 • turnOnHazard()

Messages and Methods

In order to process a message, an object needs to have a method defined for the requested task.A method is a small, well-defined piece of code that completes a specific task.For our previous example, we need to define a method to turn on the car's hazard lights.

Messages and Methods

Audi 6 BMW Z3 CorvetteCar Car Car

Car

MaxSpeed = 155

turnOnHazard()

MaxSpeed = 165

turnOnHazard()

MaxSpeed = 145

turnOnHazard()

MaxSpeed

LMaxSpeed=155

NumCars = 3

turnOnHazard()

Instance methodsEach class can have methods that are specific to each object, called instance methods.

These can only affect that object's parameters, i.e., it’s instance variables.

Example: If BMW has 4 gallons of gas and someone puts 6 more gallons of gas in his/her car, the car now has 10 gallons. The amount of gas in Audi and Corvette is unchanged.

Messages and Methods

Audi 6 BMW Z3 CorvetteCar Car Car

Car

MaxSpeed = 155

turnOnHazard()addGass(amount)

MaxSpeed = 165

turnOnHazard()addGass(amount)

MaxSpeed = 145

turnOnHazard()addGass(amount)

MaxSpeedLMaxSpeed=155NumCars = 3turnOnHazard()addGass(amount)

MethodsIt is also possible that you want information from an object; in this case, you would define a method that sends (returns) a message back to the requester containing that information.

We need to know how much gas is in our cars, so we will create a new method that returns the value of GasLevel variable for our car.

Messages and Methods

Audi 6BMW Z3

CorvetteCar

CarCar

Car

MaxSpeed = 155GasLevel = 4

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeed = 165GasLevel = 10

MaxSpeed = 145GasLevel = 6

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeedGasLevelLMaxSpeed=155NumCars = 3

addGass(amount) getGasLevel():GasLevel

turnOnHazard()

addGass(amount) getGasLevel():GasLevel

turnOnHazard()

Class methodsClass methods are used to get or manipulate information about all objects created from the class.

Typically, class methods are changing class variables. For example:

Each time we move the car in or out of the garage, we need to add/subtract one to the number of cars: carIn( ) & carOut( )Also, we may want to know how many cars are actually in the garage: getNumCars( )

Messages and Methods

Audi 6 BMW Z3 CorvetteCar Car Car

Car

MaxSpeed = 155GasLevel = 4

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeed = 165GasLevel = 10

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeed = 145GasLevel = 6

turnOnHazard()addGass(amount)getGasLevel():GasLevel

MaxSpeedGasLevelLMaxSpeed=155NumCars = 3

addGass(amount) getGasLevel():GasLevel

turnOnHazard()

carIn()

carOut()

getNumCars():NumCars

Object Oriented Programming

When writing object-oriented programs, first one must define the classes (like Car).

Then, while the program is running, the instances of the classes (objects) (such as Audi, BMW, Corvette in our example) are created.

Object Oriented Programming

Object-oriented programming allows the programmer to hide the implementation details from the other objects and the users.

In other words the implementation is transparent to the other objects or the user.

Example: Although our computers all are different “under the hood”, we don’t need to know what’s there to be able to use them.

Benefits

An object can be written and maintained separately from the rest of the program, modularity.

An object has a “public face” that it uses to communicate with other objects, but other objects can not directly access its instance variables, information hiding.

Encapsulation

Bank machineHidden data

account balancepersonal information

Interfacedeposit, withdraw, transferdisplay account information

Classes - Programming

Robot GameHidden data

locationnumber of Things

Interfacemove, turnLeftpickThing, putThing

Multiple Instances of a Class

No limit to the number of objects that can be created from a classEach object is independent. Changing one object doesn’t change the others

Interaction Among Classes

A program is composed of multiple classesClasses may contain references to other classes within the set of attributes or behavioursStart in an application class (main)

construct one or more objects and call methods associated with those objects

Schematic Design

Every class has a boxclass nameattributes/instance variablesbehaviours/methods

Arrows indicate the relationships among classes* indicates 0-many

BankAccountint acctNum Client acctHolder double balanceBankAccount(Client info) void deposit(double amt) boolean withdraw(double amt)

Bank

1

*

Client

String firstName String lastName int creditRatingClient(...) void updateCredit(double amt)

Schematic for the Robot Game

City

robotswallsthings

City()City(String descriptionFile)void showThingCounts(boolean show)

Robot

streetavenuedirectionspeedbackpack

Robot(City city, int avenue, int street,int direction, int numThings)void move()void turnLeft()void pickThing()void putThing()boolean frontIsClear()boolean isBesideThing()int countThingsInBackpack()void setSpeed(int newSpeed)int getAvenue()...

Wall

Thing

*

**

A thing may be associatedwith one robot or onelocation in the city, butnot both at the same time.

*

InheritanceThe inheriting class contains all the attributes and behaviours of the class it inherited from plus any attributes and behaviours it definesThe inheriting class can override the definition of existing methods by providing its own implementationThe code of the inheriting class consists only of the changes and additions to the base class

Inheritance Diagram

GeneralOutline

Interface

method

method

method

method

method

method

method

Fields ofThe Object

methodmethod

method

override

AdditionalFields

Why Use Inheritance?Modular coding

less code, easier to understandCode reuse

don’t break what is already workingeasier updates

May not have access to modify the original source codePolymorphism

Inheritance Terminology

Class one aboveParent class, Super class

Class one belowChild class

Class one or more aboveAncestor class, Base class

Class one or more belowDescendent class

Inheritance: Bank AccountBankAccount

int acctNum Client acctHolder double balanceBankAccount(Client info) void deposit(double amt) boolean withdraw(double amt) void printStatement()

SavingsAccountdouble interestRate double accruedInterest Time lastBalanceChangeSavingsAccount(...) void updateIntRate(double rate) void deposit(double amt) boolean withdraw(double amt)

ChequingAccountdouble minBalanceChequingAccount(…) boolean withdraw(double amt) double calcServiceFee()

Inheritance: Robot Game

increase functionality (behaviours)turnAroundpickAllThings

increase attributesstarting positionnumber of steps taken

Basic ConceptsObjects

Hidden data that is accessed and manipulated through a well-defined interface

ClassesA template or “blueprint” for creating objects, each with their own data

InheritanceA new class created by modification of an existing class

top related