Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts...

15
9/6/2018 1 Introduction to OO Concepts Written by John Bell for CS 342, Fall 2018 Based on chapters 1, 2, and 10 of “The Object-Oriented Thought Process” by Matt Weisfeld, with additional material from “UML Distilled” by Martin Fowler, and other sources. Preview Which of the following UML arrow types indicates inheritance? A. B. C. D. E.

Transcript of Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts...

Page 1: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

1

Introduction to OO Concepts

Written by John Bell for CS 342, Fall 2018

Based on chapters 1, 2, and 10 of “The Object-Oriented Thought Process” by Matt Weisfeld, with additional material from “UML

Distilled” by Martin Fowler, and other sources.

Preview

Which of the following UML arrow types indicates inheritance?

A.

B.

C.

D.

E.

Page 2: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

2

What is an Object?

• Encapsulation ( bundling together ) of related data items and associated methods.• Basic types ( ints, floats, etc. ) arrays ( collections of

items of the same type ) structs ( collections of items of different data types ) objects ( collections of data and related methods, encapsulated into a single new data type. )

• A well-defined object should represent a single semantic entity, such as a book, an airplane, a deadline, a promise, or a principal. Note that some objects may be intangible.

What color is a zebra ?

A. White with black stripes.

B. Black with white stripes.

C. Yes. ( A zebra is both. )

Page 3: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

3

Two Important Views of Objects

• Data-centric: An object is a collection of related data items representing the state of an entity, along with the methods necessary to maintain that state information.

• Service-centric: An object is a collection of related services provided by an entity, along with the data necessary to provide those services.

• Both views are correct, and well-designed objects should always conform to both definitions.

How do Classes relate to Objects?

• Programmers write classes, defining new data types.• Classes define the data items and methods that will be

contained within all objects created of the class’s type.

• Programs then instantiate new variables of the defined class data types. These variables, called instances of a class, are objects.

• Classes are to cookie cutters as objects are to cookies. Each object created from the same class has the same basic content, though details differ.

Instantiate

Classes

Objects

Page 4: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

4

Interface vs. Implementation

• The interface of a class consists solely of the class’s public method signatures ( method names, return types, and number and types of parameters only. )• ( and public data fields if any, which should be rare. )

• ALL private data, private methods, and internal code details ( including parameter names ) are part of the implementation, and should be completely hidden.

• The interface should be carefully thought out and fairly stable before being published.

• The implementation may be changed at any time, unbeknownst to the rest of the world.

Information Hiding is a key OO Concept

• The internal working details ( the implementation ) of a class should be on a strictly need-to-know basis.

• Only the interface of the class should be known to the outside world.

• This allows the internal workings to be changed at any time, without disrupting any code that uses the class.

• As a general rule, all data fields should be private, and only some of the methods made public.

• Getters and setters ( accessors and mutators ) provide controlled public access to private resources.

Page 5: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

5

Responsibility in OO Design

• In an OO program, each class has certain responsibilities, which must be clearly delineated.

• In particular, each class is responsible for maintaining and using the data contained within its own class.

• For example, the reader of a book does not turn the book’s pages. The reader sends a request to the book, asking the book to turn its own pages. The book pages belong to the book, and should not be turned by any other class.

• ( Classes must keep their hands off data that does not belong to them. )

Review

Suppose a Witch class contains a reference to a Cauldron class in a variable “pot”. What code in Witch should run when the witch puts the pot on the fire?

A. pot.temperature++;

B. pot.temperature = pot.temperature + 1;

C. pot.setTemperature( pot.getTemperature ) + 1;

D. pot.increaseTemperature( 1 );

E. pot.heat( 1 );

Page 6: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

6

UML ( Unified Modeling Language ) Class Diagrams document the

contents of classes

Book

nPages : inttitle : String

turnToPage( page : int ) : voidgetCurrentPage( void ) : int

Class Name

Class Attributes ( Data Fields )

Class Methods ( Services )

Return types

Book A lower level of detail may omit internal information.

Class Diagrams Document Access

Book

- nPages : int

+ setNumberOfPages( int )

Minus denotes a private data field

• The internal variable name and data type can be changed at any time, without affecting any code outside the Book class.

• No code outside the Book class is allowed to read or write the nPagesfield, except through public methods such as setNumberOfPages

• The setNumberOfPages method may verify the validity of its input before completing the requested change. ( Must be non-negative. )

• Even if no control is needed at this time, this approach allows for controls to be put into place easily at a later date.

Plus denotes a public method

Page 7: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

7

UML Documents Relationships Between Classes

Class A Class B A simple line indicates an unspecified relationship.

Class A Class B A normal arrow indicates accessibility

Class A Class B1 * Multiplicity - One A related to multiple BsRanges indicated by m..n

Parent Child Hollow triangle indicates inheritance

Student

Lecture

Course

Composition - A stronger bonded collection.The whole does not exist withoutthe parts, and vice-versa.

Aggregation - A collection of independent objects.

1 *

* *

Bread FlourBag

More UML Class Diagram Details

440Text : Book

: Book

An underline indicates a specific object, as opposed to a class.The variable “440Text” is an object of type Book.

Objects may be unnamed, depending on the current discussion.

Runnable Italics indicate an Interface in Java, or an Abstract Class in C++.

QuestionExam{ordered} *

Relationships may be annotated

Pilot Plane Some authors assign roles to relationships.flys is flown by

Page 8: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

8

Some More Valuable UML

UI Subsystem

CalculationSubsystem

CommunicationsSubsystem

Window Dialog

Message

Packages group related items

Encrypted

Notes have one folded corner,can be attached to anything.

ReviewWhat relationship is shown in the following UML diagram?

A. Class A is a parent of class B

B. Class B is a parent of class A

C. Class B is a parent of class C

D. Class C is a parent of class B

E. Other - Either none of the above or more than one of the above is true.

Page 9: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

9

Delegation

• A class may fulfill its responsibilities by delegating( sub ) tasks to other classes.

Homeowner

Lawn theGrass

mowLawn( ) LawnCareProfessional

mow( Lawn g )

mow( theGrass )

Assistant

trim( Lawn lawn )

trim( g )

( Note that there is no inheritance in this example. )

Inheritancea.k.a. Specialization

• Used when one concept ( class ) IS A special version of another concept ( class. )

• Saves effort and reduces errors by not duplicating code that the two classes have in common.

• Like any powerful tool, inheritance must be used properly. Misuse of inheritance can be dangerous.

• The more general class, the parent, is developed first, containing methods common to both classes.

• The more specific class, the child, inherits methods from its parent, which it can replace or augment.

Page 10: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

10

Liskov Substitution Principal

• For a class C to be a true and correct specialization of a class P, it must be possible to substitute an instance of class C in any code that is expecting an instance of class P.

• In other words, C can take the place of P anywhere that P is used, because C IS A P.

• If there is any place where a P is expected and a C cannot be used to take its place, then you do not have a true inheritance situation, and you should not be using inheritance.

P

C

Example: A Car IS A Vehicle

• The Car class contains a speed field and a drive( ) method, because it inherited them from the Vehicle class.

• The Car class can use the drive( ) method as is, or replace it with a specialized version.

• The Car class can also add additional fields and methods.

Vehicle

speed

drive()

Car

Page 11: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

11

Overloading versus Overriding

• buy( float ) overloads buy( int ).• Two or more methods in the same

scope with the same name, but different number or types of arguments.

• The method name and parameter types collectively form the method’s signature.

• drive( ) in Car overrides drive( ) in Vehicle. It replaces the inherited method within the scope of the Car class.

Vehicle

speed

drive( )

Car

drive( )buy( int )buy( float )

Access Control Under Inheritance

• - speed is private. It is not available outside Vehicle, not even to Car.

• + drive( ) is public. It is available to anyone, including Car.

• # goFaster( ) is protected. It is private to most of the world, but public to Vehicle’s descendants, such as Car.

• Vehicle.goFaster( ) can access speed.

• If Car overrides goFaster( ), then Car.goFaster( ) cannot access speed.

Vehicle

- speed

+ drive() # goFaster()

Car

Page 12: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

12

( Until someone writes Kitchen.clean( ) ! )

Inheritance vs. Aggregation/Composition( IS A versus HAS A )

Vehicle

Car

Part

Passenger

WheelEngineFrame

Human

TruckMotorcycle

contains *

is composed of *

A Car is a type of a Vehicle An Engine is a type of a Part

A Passengeris a type of a Human

Page 13: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

13

Abstract Classes

• Abstract classes have one or more methods that are declared, but not defined.

• Abstract classes cannot be instantiated, but they can be parents to descendent classes.

• Descendents of abstract classes inherit fields and any defined methods, plus an obligation to provide the undefined methods. ( Otherwise they are also abstract. )

• Pure abstract classes do not define any methods. Java terms these Interfaces.

Polymorphism

• Polymorphism occurs when a reference variable to a class type is used to refer to an object of a descendent type.

• Assume Car inherits from Vehicle and overrides drive( ):

• C++ Example:Vehicle *vptr1 = new Vehicle( ), *vptr2 = new Car( );

vptr1 -> drive( ); // Calls Vehicle.drive( )

vptr2 -> drive( ); // Calls Car.drive( )

• Java Example:Vehicle v1 = new Vehicle( ), v2 = new Car( );

v1.drive( ); // Calls Vehicle.drive( )

v2.drive( ); // Calls Car.drive( )

Page 14: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

14

Review

Which of the following relationships can be dynamically adjusted while a program is running?

A. Inheritance

B. Delegation

C. Both inheritance and delegation

D. Neither inheritance or delegation

E. 42

Parent

Child Delegate

Dangers of Improper Inheritance

• The semantics of inheritance and the LiskovSubstitution Principal must be respected.

• Using inheritance for convenience, as a lazy means of reusing code, can have disastrous results!

• Beware of the kangaroos!

Page 15: Introduction to OO Conceptsi342/Notes/1 - Introduction to OO Concepts.pdfIntroduction to OO Concepts Written by John Bell for CS 342, Fall 2018 ... Responsibility in OO Design •In

9/6/2018

15

Summary of Basic OO Concepts• Respect semantics. Encapsulate data and services

that are representative of real-world entities.

• Interface versus Implementation:• Keep public interface to a minimum, and semantically

consistent with the real-world entity.• Keep implementation as secret and private as possible.

• Responsibility - The class that owns the data should be responsible for the data. Consider a service request instead of a getter.

• Respect semantic inheritance, not convenient inheritance. Obey Liskov Substitution Principal.

• In design, always consider the trade-offs of delegation versus inheritance.