POLYMORPHISM - PowerPoint PPT Presentation

About This Presentation
Title:

POLYMORPHISM

Description:

Car is 'declared type,' while Van is 'actual type' ... we can write code that deals only with superclass (whether concrete or abstract) ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 31
Provided by: williama3
Learn more at: http://www2.hawaii.edu
Category:

less

Transcript and Presenter's Notes

Title: POLYMORPHISM


1
POLYMORPHISM
  • Quick Look Back at Inheritance
  • Polymorphism
  • Defined
  • The Key to OOP
  • The Big Payoff the Generic Button
  • Trade-offs
  • Partial Overriding

2
Quick Look Back at Inheritance
  • Remember the inheritance of private instance
    variables?
  • Weve seen that idea before!
  • just like public and private properties!
  • what can the subclass access in the diagram on
    next slide?
  • what cant it access?

3
Quick Look Back at Inheritance
public method of superclass
protected method of superclass
private methods and private instance variables of
superclass
public method of superclass
public abstract method of superclass
public instance variable of superclass
protected instance variable of superclass
4
Quick Look Back at Inheritance
  • 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!

5
A Contrived Example
  • So when we construct an instance of SubMobile, it
    makes a new City instance to pass to its
    superclasss constructor.
  • SuperMobile takes that City instance and uses it
    to instantiate a ICS111Mobile.
  • Then our instance of SubMobile calls move(),
    which it inherits.
  • This method uses the superclasss private
    instance mobile, so we must have inherited it!

6
Polymorphism
  • Remember Inheritance lecture
  • SportsCar, Van, and ICS111Mobile 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

7
Polymorphism
8
Polymorphism
  • What happens when we
  • tell SportsCar to move()?
  • (moves fast)
  • tell Van to move()?
  • (moves at a moderate speed)
  • tell ICS111Mobile to move()?
  • (sometimes moves, sometimes just sputters along!)

9
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
    responds to the same messages
  • we can use an instance of subclass as if it were
    instance of superclass
  • Car car // Declaration
  • car new Van ()// Instantiation
  • object will respond according to implementation
    defined in subclass

10
Polymorphism Defined
  • Key points about Polymorphism
  • assignment does NOT create an instance of Car,
    since new Car() is illegal, because Car is
    abstract. It is a Car, but not an instance of
    Car!
  • car.move() //will move like a Van, though we
    refer to it as a Car!
  • Car is declared type, while Van is actual
    type
  • we can only call Car methods on car since Java
    determines which methods can be called by looking
    at the declared type, i.e. Car
  • we cannot assign a superclass instance to a
    variable of subclass type because superclass
    instance does not know all the declared subtypes
    methods

11
  • / A simple example of Polymorphism. /
  • public class RaceTrack
  • private Car carOne, carTwo, carThree /they're
    all declared as Cars!/
  • public RaceTrack ()
  • carOne new SportsCar ()
  • carTwo new Van ()
  • carThree new ICS111Mobile ()
  • // but actual types are subtypes of Car
  • public void startRace() /tell Car instances to
    move/
  • carOne.move ()
  • carTwo.move ()
  • carThree.move ()
  • / Note move() called as if all were Cars,
    but
  • executed polymorphically on instances of
  • subtypes/

12
Polymorphism The Key to OOP
  • When a sending message to an instance, we do not
    need to know its exact class...
  • as long as it is a subclass that extends a
    superclass, can send the subclass any message
    that we can also send to the subclasss
    superclass
  • but message may be handled differently by
    different subclasses, so we may get different
    results

13
Polymorphism The Key to OOP
  • Classic example shapes
  • each shape subclass knows how to draw itself, but
    all do it differently simply say shape.draw()
  • See ShapesFrame.java
  • public class Shapes
  • private Shape shape1 new Triangle()
    private Shape shape2 new Square ()
  • public void drawShapes () shape1.draw
    () shape2.draw ()
  • public static void main(String args)
  • new Shapes().drawShapes()

14
Example Adding a new Shape
  • Pressing a button will draw a different shape
  • RightTriangle, Square, Circle
  • See file DrawShapeButtonFrame.java
  • What if we added a new Shape subclass?
  • Would we need to make a new DrawShapeButton for
    each Shape subclass?
  • By using polymorphism, we can add as many Shape
    subclasses as we want, without having to create a
    new DrawShapeButton for each subclass!

15
The Big Payoff of Polymorphism the Generic Button
  • / This button draws any instance of Shape.
    Since this class is written generically, we don't
    need to recompile it if we add more shapes and
    buttons /
  • class DrawShapeButton extends RoundedRectangle
  • private Shape shape
  • public DrawShapeButton(Shape shape)
  • this.shape shape
  • public voidmouseReleased(MouseEvent e)
  • shape.draw()

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). The declared type may be
abstract, but the actual type must be concrete,
as it must be instantiated.
16
More about DrawShapeButton
  • DrawShapeButton doesnt know a Square from a
    RightTriangle, but it works correctly because it
    just expects any instance of Shape
  • a subclass of Shape may not even be written until
    after DrawShapeButton has been compiled!
  • This is very general way to code
  • we can write code that deals only with superclass
    (whether concrete or abstract)
  • we can add new subclass and all code that uses
    superclass still works
  • no need to change existing code!

17
More about DrawShapeButton
  • Java compiler helps enforce this generality
  • we can only use objects that are Shape with
    DrawShapeButton, otherwise code would not compile
  • DrawShapeButton doesn't care about the actual
    type of the instance, as long as it's a Shape
  • allows many objects, possibly written by
    different people or at different times, to
    respond to the same message in very different
    ways
  • you "code to" public "interface", not private
    implementation

18
Example New Shape Application
  • To make three buttons, each of which moves a
    different Shape, just instantiate three
    DrawShapeButton and pass each a different Shape!
  • public class DrawShapeButtonFrame extends Frame
  • private Shape shape1 new RightTriangle(.
    . .)
  • private Shape shape2 new Square(. . . )
  • private Shape shape3 new Circle(. . . )
  • private DrawShapeButton button1, button2,
    button3
  • public DrawShapeButtonFrame()
  • button1 new DrawShapeButton(100, 400,
    shape1)
  • button2 new DrawShapeButton(300, 400,
    shape2)
  • button3 new DrawShapeButton(500, 400,
    shape3)
  • public static void main (String
    arguments)
  • new DrawShapeButtonFrame()

19
Trade-offs of Polymorphism
  • Type of variable limits which messages it can be
    sent
  • only messages defined by superclass
  • if subclass defines additional methods, they
    can't be called directly on a reference to
    superclass
  • In a minor way, this limits our flexibility
  • if Circle has a method getRadius() not defined in
    Shape, we can't use a generic Shape to call
    shape.getRadius()
  • why? Because all we know what a Shape can do is
    in its definition

20
Trade-offs of Polymorphism
  • But polymorphism also provides us with extra
    options
  • code is the same no matter which subclass of
    Shape is actually instantiated
  • to make a new subclass of Shape work, we dont
    need to revise, rewrite or debug methods that are
    in the Shape class already huge payoff of OOP!

21
Class Exercise
  • Create a new shape
  • Add the class to file ShapesFrame.java
  • For example, an isosceles right triangle
  • Add a new button
  • Add the button to DrawShapeButtonFrame.java
  • Note that we do not have to create a new button
    class, as the class DrawShapeButton can reference
    (point to) any instance that is a subclass of
    Shape

22
Partial Overriding
  • / Models a version of the ICS111Mobile that
    holds clowns in order to demonstrate new idea
    partial overriding. /
  • public class CrazyMobile extends ICS111Mobile
  • private BandOfClowns clowns
  • public CrazyICS111Mobile(BandOfClowns clowns)
  • this.clowns clowns
  • public void move ()
  • clowns.pileIntoCar ()
  • super.move ()
  • clowns.pileOutOfCar ()

23
Partial Overriding
  • Remember that overriding allows us to replace
    superclass definition of method
  • Partial overriding overrides superclass method
    in part
  • reusing superclass method rather than completely
    replacing it
  • calls superclass method with the same name using
    super, plus providing additional code

24
Partial Overriding
  • public void move ()
  • // add some extra functionality
  • clowns.pileIntoCar ()
  • / We want to move like the superclass moves,
    so we call superclass's move() method. No need
    to repeat code that is already written in
    ICS111Mobile's move() method!/
  • super.move ()
  • // add some more functionality
  • clowns.pileOutOfCar ()
  • // end of move()

25
Partial Overriding
  • super.move() can be called more than once
  • super.move() can even be called in another method
  • But we can use only overridden methods from
    immediate superclass super.super.move() doesn't
    work!
  • Alert what happens here if we call this.move()
    instead of super.move()?
  • Exception in thread "main" java.lang.StackOverflo
    wError

26
Polymorphism can be tricky
  • Lets say that class Garage has following method
  • public void storeCar(ICS111Mobile car)...
  • . . . and we construct a local variable with
    declared type Car and actual type
    ICS111MobileCar niceCar new
    ICS111Mobile()garage.storeCar(niceCar)//error

27
Polymorphism can be tricky
  • We cannot pass our niceCar variable into
    storeCar()
  • niceCar, as a Car, doesnt have all of
    ICS111Mobiles methods available, hence a
    parameter type mismatch
  • This is the corrected code
  • ICS111Mobile niceCar new ICS111Mobile()
  • garage.storeCar(niceCar)

28
Polymorphism can be tricky
  • 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 ICS111Mobile (declared type of
    formal parameter) . . . so wont work!

29
Class Exercise
  • Whats the output?
  • See Tracing.java
  • A similar problem will be on the next exam

30
Example Code
  • Check out the SketchApplication files
  • SketchApplication contains classes Cursor
    DrawButton
  • See class websites Example Code link
  • Class Cursor contains class Point
  • Class DrawButton has 4 subclasses
  • UpButton, DownButton, LeftButton, RightButton
  • This is an example of polymorphism
  • Depending on what type of DrawButton we click
    (i.e., UpButton, DownButton), the line will move
    up, down, etc.
Write a Comment
User Comments (0)
About PowerShow.com