22
© 2006 Pearson Education Polymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

Embed Size (px)

Citation preview

Page 1: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 1 of 22

POLYMORPHISM

• Polymorphism

• Partial Overriding

• OOP Review

Page 2: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 2 of 22

Quick Look Back at Inheritance

• Remember the “pseudo-inheritance” of private instance variables from last lecture?

• We’ve seen that idea before! just like public and private properties! what can the subclass access in the following diagram?

What can’t it?

• Remember that, when a class provides public methods, those methods can alter private data! similarly, inherited methods can alter private data of the

superclass therefore we do “pseudo-inherit” private properties because

the normally inherited methods might need to access them!

public method of superclass

public method of superclass

protected instance variable of superclass

protected instance variable of superclass

public abstract method of superclass

protected method of superclass

private methods and private instance variables of

superclass

Page 3: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 3 of 22

Quick Example

package ContrivedExample;

public class SuperClass {

private CSMobile _car;

public SuperClass(City city) {

_car = new CSMobile(city);

}

public void moveCSMobile() {

_car.takeTrip();

}

}

package ContrivedExample;

public class SubClass extends SuperClass {

public SubClass() {

super(new City());

this.moveCSMobile();

}

}

• So when we construct an instance of SubClass, it makes a new City instance to pass to its superclass’s constructor. SuperClass takes that City instance and uses it to instantiate a CSMobile. Then our instance of SubC calls moveCSMobile(), which it inherits. This method call affects the superclass’s private instance variable _car, so we must have “pseudo-inherited” it!

Page 4: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 4 of 22

Polymorphism

Remember last lecture: SportsCar, Van, and CSMobile are all

subclasses of the Car class Car has an abstract move() method that each of

its subclasses define however, each of its subclasses defines this

method differently

• Thus each subclass responds to move() differently

• What happens when we: tell SportsCar to move()?

(moves fast) tell Van to move()?

(moves at a moderate speed) tell CSMobile to move()?

(sometimes moves, sometimes just sputters along!)

Car

Van CSMobile SportsCar

Page 5: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 5 of 22

Polymorphism defined

• Polymorphism is a fancy word for “multiple forms,” e.g., multiple forms of response to the same message

• Key points about Polymorphism: subclass inherits methods from superclass, it can

respond to at the same messages can refer to an instance of subclass as if it were an

instance of superclass• do this for generality - stay tuned.

// DeclarationCar myCar;

// InstantiationmyCar = new Van();

object will respond according to implementation defined in subclass!

Note: assignment is NOT creating an instance of Car, which can only be done by new and is illegal, given that Car is abstract. It “is a” Car, but not an instance of Car!myCar.move(); // myCar will move like a Van,

// though we refer to it as a Car!

Car is “declared type,” while Van is “actual type” can only call Car methods on myCar since Java

determines which methods can be called by looking at declared type, Car

Note: assigning a superclass instance to a variable of subclass type doesn’t work because all the declared subtype’s methods can’t be supported by the superclass’ instance.

Page 6: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 6 of 22

Take me out to the Racetrack/**

* A simple example of Polymorphism.

*/

public class RaceTrack {

private Car _carOne, _carTwo, _carThree;

// note they're all declared as Cars

public RaceTrack() {

_carOne = new SportsCar();

_carTwo = new Van();

_carThree = new CSMobile();

// but actual types are subtypes of Car

}

public void startRace() {

// tell Car instances to move

_carOne.move();

_carTwo.move();

_carThree.move();

// Note: moves coded polymorphically as if

// all were Cars, but methods are called on

// instances of subtypes

}

} // end of class RaceTrack

• This code doesn’t really show off the power of polymorphism, though it would let us choose different kinds of actual Cars without changing the startRace() method

Page 7: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 7 of 22

Polymorphism: Key to OOP

• When a sending message to an instance, we do not need to know its exact class... as long as it is class that extends superclass, can send

it any message we can send to superclass but message may be handled by a subclass, so we may

get different results

• Classic example: shapes (similar to RaceTrack example) each shape subclass knows how to draw itself, but all

do it differently• simply say _shape.draw()

public class ShapeApp extends wheels.users.Frame {private Shape _shape1, _shape2;

public ShapeApp() {

super(); _shape1 = new Triangle(); _shape2 = new Square(); }

public void drawShapes() { _shape1.draw();

_shape2.draw();}

public static void main(String[] argv) { ShapeApp app = new ShapeApp(); }}

• Let’s see the real power of polymorphism!!

Page 8: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 8 of 22

Example: Adding a new Car

• Remember our Button example? VanButton CSMobileButton SportsCarButton

• What if we added a new Car subclass? Would we need to make a new PushButton subclass?

• We can rewrite this example using Polymorphism, and then we can add as many Car subclasses as we can imagine!

Page 9: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 9 of 22

The Big Payoff of Polymorphism: the Generic Button

/**

* This button will move any instance of Car,

* replacing the three subclasses we wrote last

* lecture! Since this class is written

* generically, no need to recompile this

* class if we add more cars and buttons to our

* app!

*/

public class MoveCarButton extends PushButton {

private Car _myCar;

public MoveCarButton(Car myCar) {

super( “Move Car” );

_myCar = myCar;

}

public void release() {

_myCar.move();

}

} // end of class MoveCarButton

declared type is a generic parameter! Caller passes in an instance of a specific actual type (not to be confused with “actual” parameter, which it also is). While the declared type may be abstract, the actual type must be concrete to be instantiated.

Page 10: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 10 of 22

More about MoveCarButton

• MoveCarButton doesn’t know a SportsCar from a CSMobile, but it works correctly because it is just expecting an instance of Car a subclass of Car may not even be written until

after MoveCarButton has been compiled!

• Very general way to code can write code that deals only with superclass

(whether class is concrete or abstract) can add new subclass at any time and all

superclass code will still work -- no need to change existing code!

• Java compiler helps enforce this generality can only use objects that “are” Cars with MoveCarButton,otherwise code would not compile

but MoveCarButton does not care about actual type of instance, as long as it is a Car

allows many objects, possibly written by different people or at different times, to respond to same message in very different ways

you code to public interface, not private implementation

Page 11: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 11 of 22

Example: New App

• To make three buttons, each of which moves a different Car, just instantiate three MoveCarButtons and pass each a different Car!

public class CarApp extends wheels.SP.Frame { private Car _carOne, _carTwo, _carThree;private MoveCarButton _buttonOne, _buttonTwo,

_buttonThree;

public CarApp() { super(); _carOne = new Van(); _carTwo = new CSMobile(); _carThree = new SportsCar();

_buttonOne = new MoveCarButton(_carOne); _buttonTwo = new MoveCarButton(_carTwo); _buttonThree = new MoveCarButton(_carThree); // code to position buttons elided } public static void main(String[] argv) { CarApp app = new CarApp(); }} // end of class CarApp

Page 12: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 12 of 22

The Polymorphic Way

• Still not convinced? Let’s compare this App to the one we wrote last lecture:

public class CarApp extends wheels.SP.Frame

{

private Van _van;

private VanButton _vanButton;

private CSMobile _csMobile;

private CSMobileButton _csMobileButton;

private SportsCar _sportsCar;

private SportsCarButton _sportsButton;

public CarApp() {

super();

// rest of constructor elided

}

} // end of class CarApp

Page 13: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 13 of 22

Trade-offs of Polymorphism

• Type of variable determines which messages can be sent to any instance only messages defined by superclass if subclass defines additional methods, cannot be

invoked directly through reference to superclass

• In a minor way, this limits our flexibility if Van has a method called storeGroceries()

which is not defined in Car, we cannot use a generic Car button to call _car.storeGroceries()

why? Because all the button knows about Car via its definition is that it can tell it to do whatever a Car knows how to do

• But polymorphism also provides us with extra options code remains the same no matter which subclass of Car is actually instantiated

if new subclass of Car works, don’t need to revise, rewrite or debug methods that are coded in terms of generic Car again — huge payoff of OOP!

Batmobile, BMW, Buick, Cadillac, Chrysler, CSMobile...

Page 14: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 14 of 22

Send in the Clowns: Partial Overriding (1 of 2)

/**

* Models a version of the CSMobile that

* holds clowns in order to demonstrate new

* idea: partial overriding.

*/

public class CrazyCSMobile extends CSMobile

{

private BandOfClowns _clowns;

public CrazyCSMobile(BandOfClowns boc) {

super();

_clowns = boc;

}

public void move() {

_clowns.pileIntoCar();

super.move();

_clowns.pileOutOfCar();

}

} // end of class CrazyCSMobile

Page 15: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 15 of 22

• Remember that overriding allows us to replace superclass’ definition of method

• Partial overriding is overriding superclass’ method in part: reusing functionality from superclass’ method

rather than completely replacing it calling superclass’ method of the same name

using super, plus providing additional code

public void move() { // add some extra functionality _clowns.pileIntoCar(); /** * We want to move like the superclass, so * we call superclass’ move() method. No * need to repeat code that is already * written in CSMobile’s move() method! */ super.move();

// add some more functionality_clowns.pileOutOfCar();} // end of move()

Send in the Clowns: Partial Overriding (2 of 2)

note: can call this from anywhere, even repeatedly...

Page 16: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 16 of 22

Partial Overriding (2 of 2)

• super.move() can be called more than once

• super.move() can even be called in another method

• Illustrates how subclass can use superclass’ method to manipulate superclass’ private property which remains hidden from subclass

• what would happen here if we called this.move() instead of super.move()?Exception in thread "main" java.lang.StackOverflowError

Page 17: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 17 of 22

Polymorphism can be tricky.

• Let’s say that class Garage has following method…

public void storeCar(CSMobile myCar) {...} . . . and we construct a local variable

with declared type Car and actual type CSMobile:

Car niceCar; // DeclarationniceCar = new CSMobile(); //Instantiation

• Can we pass our niceCar variable into the storeCar() method?

• No! storeCar() is expecting to use any methods of the

parameter’s declared type (CSMobile) and Java will similarly only invoke Car methods on niceCar (but use CSMobile’s implementation details).

In short: niceCar, as a Car, doesn’t have all of CSMobile’s methods available, hence a parameter type mismatch.

• Declared type of actual parameter must be same class (or subclass) of declared type of formal parameter Car (declared type of actual parameter) is superclass of CSMobile (declared type of formal parameter) . . . so won’t work!

Page 18: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 18 of 22

OOP Review! (1 of 4)

• Which of these statements applies to polymorphism?1) Subclasses inherit all of the capabilities and attributes of their superclasses2) Using polymorphism, the programmer can create multiple instances of the same object3) Polymorphism allows different objects to respond to the same message in different ways4) Depending on the parameters used, a method will output a different return value5) The Animal superclass of the animal kingdom is polymorphic

• Your class Cat has the method:

public Bird catchBird(Bird birdToCatch) {...}

Your class Canary extends class Bird which extends from class Animal. Your compile-errorleads you to this block of code in your Cat class:

Animal tweetyBoid = new Bird();this.catchBird(tweetyBoid); ERROR

points to this line

Page 19: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 19 of 22

OOP Review! (2 of 4)

Why won’t this compile? (one answer is correct)1) You are trying to pass tweetyBoid as class Animal when your Cat’s catchBird method

takes a Canary.2) You are trying to pass tweetyBoid as class Animal when your Cat’s catchBird method takes a Bird.3) You should explicitly call _myCat.catchBird(tweetyBoid) within your Cat class.4) You must change Animal tweetyBoid = new Bird();

so that it instantiates a Canary instead: Animal tweetyBoid = new Canary();

Page 20: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 20 of 22

OOP Review! (3 of 4)

• Consider the following (non-useful) code fragment (a.k.a. Parameters Review):

public void eat(Food food) { // Food is concrete food.cook(); food = new Food(); food.beDigested();}

From somewhere else in the program, we call:animal.eat(fruit); // fruit is of type Food

What happens to fruit? (2 correct answers)1) It gets cooked and digested.2) It gets digested, but not cooked.3) Nothing; a copy of fruit gets passed as a parameter, not the actual value pointed to by fruit.4) It gets cooked, but not digested.5) When the eat method returns, fruit refers to a different instance of the Food class.6) When the eat method returns, fruit refers to

the same instance of the Food class as it did before we called eat().

Page 21: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 21 of 22

OOP Review! (4 of 4)

• Which of the following statements about parameters is (are) correct?1) Parameters that have been received by a method are — by definition — instance variables.2) If class B is a subclass of class A, then, for methods which are declared in A, those methods by the same name in B must use only the parameters that are defined in A’s methods and no others. 3) Formal parameters are — by definition — local

variables.4) Actual parameters may be instances of a subclass of the type declared in the formal parameter.5) Parameters are declared by stating first the name for the parameter, and then the class

type of the parameter.6) An instance of a subclass may be substituted for an instance of its superclass in an actual

parameter just as an instance of a superclass may serve as a substitute for an instance of its

subclass in the same situation.

Page 22: © 2006 Pearson EducationPolymorphism 1 of 22 POLYMORPHISM Polymorphism Partial Overriding OOP Review

© 2006 Pearson EducationPolymorphism 22 of 22