View
215
Download
2
Tags:
Embed Size (px)
Citation preview
11
Working with ClassesWorking with Classes
Chapter 6Chapter 6
22
Class definition Class definition
A class is a collection of data and routines that A class is a collection of data and routines that share a well-defined responsibility or provide share a well-defined responsibility or provide provides a cohesive set of services.provides a cohesive set of services.
As programmer, you can ignore the rest of As programmer, you can ignore the rest of program while you are working on any part of program while you are working on any part of code. This is accomplished by implementing code. This is accomplished by implementing classesclasses
33
Abstract Data Types (ADTs)Abstract Data Types (ADTs)
Understanding ADTs is essential to understanding Understanding ADTs is essential to understanding object-oriented programming object-oriented programming
ADT is a collection of data and operations that work ADT is a collection of data and operations that work on that dataon that data
ADT is used to manipulate real-world entitiesADT is used to manipulate real-world entities The operations:The operations:
describe the data to the rest of the program and describe the data to the rest of the program and allow the rest of the program to change the data allow the rest of the program to change the data
44
Benefits of Using ADTsBenefits of Using ADTs
HideHide implementation detailsimplementation details Changes don’t affect the whole programChanges don’t affect the whole program You can make the interface more informativeYou can make the interface more informative It’s easier to improve performanceIt’s easier to improve performance The program becomes more self-documentingThe program becomes more self-documenting You don’t have to pass data all over your programYou don’t have to pass data all over your program You’re able to work with real-world entities ratherYou’re able to work with real-world entities rather
55
Examples of ADTs and likely operationsExamples of ADTs and likely operations
BlenderBlender Turn onTurn on Turn offTurn off Set speedSet speed
Cruise ControlCruise Control Set speedSet speed Get current settings Get current settings Resume former speed Resume former speed Deactivate Deactivate
66
Examples of ADTs and likely operationsExamples of ADTs and likely operations
Fuel TankFuel Tank Fill tankFill tank Drain tankDrain tank Get tank capacityGet tank capacity Get tank statusGet tank status
MenuMenu Start new menu Start new menu Delete menu Delete menu Add menu item Add menu item Remove menu itemRemove menu item Activate menu item Activate menu item Display menuDisplay menu Hide menuHide menu Get menu choice Get menu choice
77
Examples of ADTs and likely operationsExamples of ADTs and likely operations
StackStack Initialize stackInitialize stack Push item onto stackPush item onto stack Pop item from stackPop item from stack Read top of stackRead top of stack
FileFile Open fileOpen file Read fileRead file Write fileWrite file Close fileClose file Set current file locationSet current file location
88
Examples of ADTs and likely operationsExamples of ADTs and likely operations
ElevatorElevator Move up one floorMove up one floor Move down one floorMove down one floor Move to specific floorMove to specific floor Report current floorReport current floor Return to home floorReturn to home floor
Light Light Turn on Turn on Turn offTurn off
99
ListList Initialize Initialize InsertInsert RemoveRemove ReadRead
1010
ADT GuidesADT Guides
Treat common objects such as files as ADTsTreat common objects such as files as ADTs Treat even simple items as ADTsTreat even simple items as ADTs Refer to an ADT independently of the Refer to an ADT independently of the
medium it’s stored onmedium it’s stored on
1111
Good Class InterfacesGood Class Interfaces
To create a high quality class we must create a To create a high quality class we must create a good interface good interface
Class interface is collection of Class interface is collection of public routinespublic routines that could be seen and used by other programs that could be seen and used by other programs or classes or classes
1212
1313
This class might have additional routines and This class might have additional routines and data to support these services, but users of the data to support these services, but users of the class class don’t needdon’t need to know anything about them to know anything about them
The following example shows bad class The following example shows bad class interface interface
1414It’s hard to see any connection among the command stack and report routines or the global data.
1515
It could be revised to present a consistent abstraction as illustrated It could be revised to present a consistent abstraction as illustrated
in the following examplein the following example
some of these routines were moved to other, more appropriate classes and some were converted to private routines used by InitializeProgram() and
ShutDownProgram().
1616
More Class Interface guidelinesMore Class Interface guidelines Provide services in pairs with their opposites Provide services in pairs with their opposites If you If you
have an operation that turns a light on, you’ll have an operation that turns a light on, you’ll probably need one to turn it off. If you have an probably need one to turn it off. If you have an operation to add an item to a list, you’ll probably operation to add an item to a list, you’ll probably need one to delete an item from the list.need one to delete an item from the list.
Move unrelated information to another class Move unrelated information to another class if you if you found that half a class’s routines work with half the found that half a class’s routines work with half the class’s data, and half the routines work with the other class’s data, and half the routines work with the other half of the data .. Break them up!half of the data .. Break them up!
1717
Design and Implementation IssuesDesign and Implementation Issues
1818
Containment (“has a” relationships)Containment (“has a” relationships)
Containment is the simple idea that a class Containment is the simple idea that a class containscontains
One way of thinking of containment is as a One way of thinking of containment is as a “has a” relationship“has a” relationship
an employee “has a” name, “has a” phone an employee “has a” name, “has a” phone number, and “has a” tax ID. Therefore .. name, number, and “has a” tax ID. Therefore .. name, phone number, or tax ID phone number, or tax ID member datamember data (attributes) of the (attributes) of the Employee Employee class class
1919
Containment (“has a” relationships) .....Containment (“has a” relationships) .....
Number of data elements:Number of data elements:
““7±2” is a number of items a person can remember 7±2” is a number of items a person can remember while performing other tasks.while performing other tasks.
If a class contains more than about seven data If a class contains more than about seven data members, the class should be decomposed into members, the class should be decomposed into multiple smaller classes.multiple smaller classes.
2020
Inheritance (“is a” relationships)Inheritance (“is a” relationships)
Applied when one class is a specialization of Applied when one class is a specialization of another class another class
Aims to create simpler code by defining a base Aims to create simpler code by defining a base class that specifies class that specifies common elementscommon elements of two of two or more derived classesor more derived classes
The common elements can be routine The common elements can be routine interfaces, implementations, data members, or interfaces, implementations, data members, or data types data types
2121
Inheritance (“is a” relationships) …Inheritance (“is a” relationships) …
the new class “the new class “is ais a” more specialized version ” more specialized version of the older classof the older class
Inheritance adds complexity to a program, Inheritance adds complexity to a program, therefore, it is a dangerous techniquetherefore, it is a dangerous technique
Examples: in UOB; Instructor is an Examples: in UOB; Instructor is an employee .. So instructor class is derived from employee .. So instructor class is derived from employee class.employee class.
2222
Member Functions and Data GuidelinesMember Functions and Data Guidelines
Keep the number of routines in a class as Keep the number of routines in a class as small as possiblesmall as possible
Minimize direct and indirect routine calls to Minimize direct and indirect routine calls to other classesother classes
2323
Summary of Reasons to Create a ClassSummary of Reasons to Create a Class
Model real-world objectsModel real-world objects Reduce complexityReduce complexity Isolate complexityIsolate complexity Hide implementation detailsHide implementation details Limit effects of changesLimit effects of changes
2424
Summary of Reasons to Create a Class…Summary of Reasons to Create a Class…
Hide global dataHide global data Streamline parameter passingStreamline parameter passing Make central points of controlMake central points of control Facilitate reusable codeFacilitate reusable code Package related operationsPackage related operations