34
Abstraction: Polymorphism, pt. 1 Abstracting Objects

Abstraction: Polymorphism, pt. 1 Abstracting Objects

Embed Size (px)

Citation preview

Page 1: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Abstraction:Polymorphism, pt. 1

Abstracting Objects

Page 2: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Polymorphism is one of the central ideas of object-orientation (OO) – that a single object may take on multiple different roles within a program.

• It is closely related to inheritance in class hierarchies.

Page 3: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• The word originates from Greek, meaning "having multiple forms.”– “poly”: many– “morph”: forms

Page 4: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Some roles treat the object as it relates to its information content and true conceptual purpose within the program. (derived class)

• Other roles may exist as an extreme abstraction of its true purpose, extracting a single aspect of the “true” object to allow abstracted methods to utilize it. (base class)

Page 5: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Ideal Program Division

Control,UI Data

Algorithms

Page 6: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism• There are times when we do not need

all the specific details of object, but merely a few pieces.– For sorting, we merely need a way to

determine the ordering of two same-type objects – we could care less if they are ints or strings, for example.

– A… “least common denominator”, if you will, among many types.

– Recall templates and generic programming

Page 7: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• In order to facilitate this, a programmer may create custom types for the sole purpose of representing each such role.– In Java, these are called interfaces.– Each such custom type declares a set of

methods necessary to fulfill the functionalities of that role.• For the last slide’s example, we would need

a comparison method.

Page 8: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• The idea is that each such custom type provides the minimum specification and blueprint necessary for performing that role.– This custom type is then implemented

by classes in order to perform the represented role.

Page 9: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Since the specification and method names are declared in the custom type, those methods can be accessed through the custom type, without needing more specific type information.

• The actual implementation is left to each implementing (specific) class.

Page 10: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

• For a starter example, let’s suppose we want to use polymorphism to calculate geometrical properties of shapes.– The user first specifies a shape, with its

relevant parameters.– Afterward, the user may ask for its

properties derived from its parameters, or for actions to be performed on it.

Page 11: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++• Take a couple of minutes and team up

to discuss shapes, parameters, properties, and actions.–What are some shapes?• Circle, square, triangle, …

–What parameters do they have?• Edge thickness and color, fill, fill color, …

–What properties do they have?• perimeter length, area, …

–What actions may be performed?• for it to be drawn, …

Page 12: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

• We note that perimeter length and area are common properties of any shape.

• Shapes also commonly have visual forms.

• Thus, these are all reasonable properties for a common “Shape” role to have within our program.

Page 13: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

class Shape{

public:virtual double area() = 0;virtual double perimeter() = 0;

}

• The “= 0” on each method indicates that our class Shape does not define the method – it is the responsibility of any class fulfilling this role to implement them instead.

Page 14: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

class Shape{

public:virtual double area() = 0;virtual double perimeter() = 0;

}

• The keyword “virtual” on the methods indicates that Shape expects implementing classes to provide their own definition, and will allow those to be accessed from the Shape perspective.

Page 15: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

• Note: because the area() and perimeter() methods have no implementation within Shape, it is not possible to create an instance of Shape directly.

• Instead, the point is to have other classes implement the Shape role and to be able to use them from that perspective.

Page 16: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

class Circle: public Shape{

public:Circle(double r);double area();double perimeter();void draw();

private:double radius;

}

Page 17: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

double Circle::area(){

// Assuming a predefined PI constant.return PI * radius * radius;

}Circle::Circle(double r){

radius = r;}

/* Implementation of the other methods left to the imagination. */

Page 18: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

class Circle: public Shape{

public:Circle(double r);double area();double perimeter();void draw();

private:double radius;

}

Note the phrasing here – the colon indicates that Circle is inheriting the specifications

and preexisting blueprint of the type Shape. The “public” keyword says that we can use Circle objects as if they were Shape objects, with access to the virtual functions declared

in Shape.

Page 19: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Exercise 1

• Create class declarations for Shape and Square – omit draw()

• Create method definitions for Square• Create a small main() to create a few

squares of various sides, then output their areas and perimeters.

• Compile and run

Page 20: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Exercise 2

• Now in your main(), create an object that is just a Shape, not a Square.

• Compile • What is (are) the error message(s)?

Page 21: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism in C++

• If a class does not provide an implementation of a “pure” virtual method, it is impossible to directly instantiate that class.– This includes cases where an object

does not define a virtual method declared in its parent class, as would happen if we left area() undefined within our Circle class.

Page 22: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Polymorphism allows the programmer to provide alternate, abstracted views of an object.– These “views” will limit access to class

fields and methods, exposing only those defined as part of that “view.”

– In a manner of speaking, the type Shape exists to provide a restricted “view” of Circle.

Page 23: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Class Hierarchy

• Another way to look at it is that the classes form a hierarchy, with the base class capturing the fundamental qualities the classes have in common– Classes in the tree under the base class may be

described in terms of the base class

• Derived classes then inherit the qualities of the base class whence they are derived, and perhaps add to or tweak it– Subclass functions override those of their

superclass

Page 24: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Polymorphism allows the programmer to provide alternate, abstracted views of an object.–While this isn’t useful if all we have is Circle, the reasoning becomes more important with Square, Pentagon, and Hexagon (for example).

– Squares aren’t Circles, but they are both Shapes, with Shape properties.

Page 25: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• All of the following are legal code lines, assuming good class definitions.

Shape* s1 = new Circle(4);Shape* s2 = new Square(4);Shape* s3 = new Pentagon(4);

Page 26: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Suppose, then, that we have vector<Shape*> shapeList, and want to sum up the area of all the stored, referenced Shapes.

double areaSum = 0;

for(int i=0; i < shapeList.size(); i++)areaSum += shapeList[i]->area();

Page 27: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• This is but one example of polymorphism.

• Others:– Human and Computer in interactive

games– “Tools” in photo-editing software can be

implemented this way– Quotes in example in book

Page 28: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Questions?

Page 29: Abstraction: Polymorphism, pt. 1 Abstracting Objects

C++ Practicalities

• Note how we’re storing each Shape via reference.– This is because in creating a by-value

variable of Shape, it is attached directly to an inherent Shape instance.• For one, this is impossible to instantiate, as

Shape has pure virtual methods.• Secondly, that instance would be of exactly

type Shape – attempting assignment would be on an implied Shape::operator=().

Page 30: Abstraction: Polymorphism, pt. 1 Abstracting Objects

C++ Practicalities

• Note how we’re storing each Shape via pointer– Use of polymorphism in C++ requires

handling objects via their pointers• A pointer of a subclass can always be stored

as a variable of its superclass • Technically, through polymorphism, a

pointer of a subclass is a pointer to an instance of the superclass – just with further specification.

Page 31: Abstraction: Polymorphism, pt. 1 Abstracting Objects

A Quick Note

• At this point in the class, we will not be examining full “inheritance.”– Understanding and being able to use

polymorphism is a large enough issue in and of itself at this time.

– The main difference: full inheritance allows for pre-defined methods and fields; actual functionality is, well, inherited.

Page 32: Abstraction: Polymorphism, pt. 1 Abstracting Objects

A Quick Note

• While our present example used only virtual, undefined methods in the base type (Shape), this is not a strict requirement of C++; more can be inherited.– Our present aim is to understand the

design goals behind polymorphism… which also affects inheritance in C++.

Page 33: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Polymorphism

• Polymorphism allows for multiple classes to share similar abstract views that may be seen as a single “role”.– Very distinct, different types sometimes

share functionally similar methods.– The implementation of these methods

may be specific to each implementing class, and is not directly sharable.

Page 34: Abstraction: Polymorphism, pt. 1 Abstracting Objects

Questions?