Presentation is loading. Please wait.

Presentation is loading. Please wait.

POLYMORPHISM Polymorphism Partial Overriding OOP Review.

Similar presentations


Presentation on theme: "POLYMORPHISM Polymorphism Partial Overriding OOP Review."— Presentation transcript:

1 POLYMORPHISM Polymorphism Partial Overriding OOP Review

2 Quick Look Back at Inheritance
Remember how Andy mentioned “pseudo- inheritance” 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 protected method of superclass public method of superclass private methods and private instance variables of superclass public abstract method of superclass protected instance variable of superclass protected instance variable of superclass

3 Quick Example package ContrivedExample; public class SuperC { private CS15Mobile _car; public SuperC(City city) { _car = new CS15Mobile(city); } public void move15Mobile() { _car.takeTrip(); public class SubC extends SuperC { public SubC() { super(new City(“Providence”)); this.move15Mobile(); So when we construct an instance of SubC, it makes a new City instance to pass to its superclass’s constructor. SuperC takes that City instance and uses it to instantiate a CS15Mobile. Then our instance of SubC calls move15Mobile(), which it inherits. This method call affects the superclass’s private instance variable _car, so we must have “pseudo-inherited” it!

4 Polymorphism Remember last lecture:
Car SportsCar Van CS15Mobile Remember last lecture: SportsCar, Van, and CS15Mobile 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 CS15Mobile to move()? (sometimes moves, sometimes just sputters along!)

5 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. Car myCar = 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.

6 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 CS15Mobile(); // 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 Who will win the race? 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

7 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!! What if we wanted to draw two Squares instead?

8 Example: Adding a new Car
Remember our Button example? StationWagonButton CS15MobileButton 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!

9 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.

10 More about MoveCarButton
MoveCarButton doesn’t know a SportsCar from a CS15Mobile, 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

11 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 CS15Mobile(); _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

12 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 CS15Mobile _15mobile; private CS15MobileButton _15Button; private SportsCar _sportsCar; private SportsCarButton _sportsButton; public CarApp() { super(); // rest of constructor elided } } // end of class CarApp Holy unnecessary classes, Batman!! Think about special casing buttons to cars... there are hundreds of cars! Acura Integra, Acura NSX, Audi A4, A6...

13 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, CS15Mobile...

14 Send in the clowns! /** * Models a version of the CS15Mobile that
* holds clowns in order to demonstrate new * idea: partial overriding. */ public class CrazyCS15Mobile extends CS15Mobile { private BandOfClowns _clowns; public CrazyCS15Mobile(BandOfClowns boc) { super(); _clowns = boc; } public void move() { _clowns.pileIntoCar(); super.move(); _clowns.pileOutOfCar(); } // end of class CrazyCS15Mobile

15 Partial Overriding 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 CS15Mobile’s move() method! */ super.move(); // add some more functionality _clowns.pileOutOfCar(); } // end of move() note: can call this from anywhere, even repeatedly...

16 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

17 Polymorphism can be tricky.
Let’s say that class Garage has following method… public void storeCar(CS15Mobile myCar) {...} . . . and we construct a local variable with declared type Car and actual type CS15Mobile: Car niceCar = new CS15Mobile(); Can we pass our niceCar variable into the storeCar() method? No! storeCar() is expecting to use any methods of the parameter’s declared type (CS15Mobile) and Java will similarly only invoke Car methods on niceCar (but use CS15Mobile’s implementation details). In short: niceCar, as a Car, doesn’t have all of CS15Mobile’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 CS15Mobile (declared type of formal parameter) so won’t work!

18 OOP Review! (1 of 4) Which of these statements applies to polymorphism? 1) Subclasses inherit all of the capabilities and attributes of their superclasses 2) Using polymorphism, the programmer can create multiple instances of the same object 3) Polymorphism allows different objects to respond to the same message in different ways 4) Depending on the parameters used, a method will output a different return value 5) 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-error leads you to this block of code in your Cat class: Animal tweetyBoid = new Bird(); this.catchBird(tweetyBoid); ERROR points to this line

19 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 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(); 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

20 OOP Review! (3 of 4) 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) It gets garbage collected. 7) When the eat method returns, fruit refers to the same instance of the Food class as it did before we called eat().

21 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.

22 Announcements… TAPlayhouse out! More…?


Download ppt "POLYMORPHISM Polymorphism Partial Overriding OOP Review."

Similar presentations


Ads by Google