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

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
Pet-able! Lecture 6 Interfaces 1 of 58. Inheritance - Review (Part I) ●Review of Inheritance o a method of modeling similar capabilities among similar.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance (notes for 10/26 lecture). Inheritance Inheritance is the last of the relationships we will study this semester. Inheritance is (syntactically)
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object-oriented Programming Concepts
Chapter 10 Classes Continued
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Abstract classes and Interfaces. Abstract classes.
Lecture 7 Polymorphism. Review: Constructors ●Parenthesis after constructor, not in class declaration ●The constructor makes the SamBot – do not “ new.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods.
© 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Local Variables Garbage collection. © 2006 Pearson EducationParameters2 of 10 Using Accessors and Mutators Together What if you want to get a property.
Andries van Dam  /01/15 1/38 Initial Questionnaire – The Results Are In! 56% of all students in CS15 have no prior coding experience! 81% of all.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
© 2006 Pearson Education Inheritance 1 of 31 INHERITANCE Class Hierarchies Extending Objects Abstract Methods Abstract Classes Overriding Methods protected.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Programming in Java CSCI-2220 Object Oriented Programming.
QUEUES What are Queues? Creating a Queue Enqueuing and Dequeuing Testing for an Empty Queue.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
© 2006 Pearson EducationDesign Patterns1 of 20 A Final Example: A Traffic Light Let’s model a traffic light! – here’s the spec: Have a column of two circles.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Overview of C++ Polymorphism
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
BY:- TOPS Technologies
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Sections Inheritance and Abstract Classes
Inheritance and Polymorphism
POLYMORPHISM Polymorphism Partial Overriding OOP Review.
Week 6 Object-Oriented Programming (2): Polymorphism
Java Inheritance.
Fundaments of Game Design
Overview of C++ Polymorphism
Presentation transcript:

© 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 protected instance variable of superclass public abstract method of superclass protected method of superclass private methods and private instance variables of superclass

© 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!

© 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

© 2006 Pearson EducationPolymorphism 5 of 22 Polymorphism defined Polymorphism is a fancy word for “multiple forms,” ­e­e.g., multiple forms of response to the same message Key points about Polymorphism: ­s­subclass inherits methods from superclass, it can respond to at the same messages ­c­can refer to an instance of subclass as if it were an instance of superclass do this for generality - stay tuned. // Declaration Car myCar; // Instantiation myCar = new Van(); ­o­object will respond according to implementation defined in subclass! ­N­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! ­C­Car is “declared type,” while Van is “actual type” ­c­can only call Car methods on myCar since Java determines which methods can be called by looking at declared type, Car ­N­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.

© 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 Car s without changing the startRace() method

© 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!!

© 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!

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

© 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

© 2006 Pearson EducationPolymorphism 11 of 22 Example: New App To make three buttons, each of which moves a different Car, just instantiate three MoveCarButton s 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

© 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

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

© 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

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

© 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

© 2006 Pearson EducationPolymorphism 17 of 22 Polymorphism can be tricky. Let’s say that class Garage has following method… p ublic void storeCar(CSMobile myCar) {...}... and we construct a local variable with declared type Car and actual type CSMobile: C ar niceCar; // Declaration niceCar = new CSMobile(); //Instantiation Can we pass our niceCar variable into the storeCar() method? No! ­s­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). ­I­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 ­C­Car (declared type of actual parameter) is superclass of CSMobile (declared type of formal parameter)... so won’t work!

© 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 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

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

© 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().

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

© 2006 Pearson EducationPolymorphism 22 of 22