Lecture%20I%20-%20Polymorphism - PowerPoint PPT Presentation

About This Presentation
Title:

Lecture%20I%20-%20Polymorphism

Description:

Paint Brush Application. Paint Brush. Paint Brush application. Slide 21 of 66. Lecture I. Paint-brush application design. Consider the design of a paint-brush ... – PowerPoint PPT presentation

Number of Views:117
Avg rating:3.0/5.0
Slides: 67
Provided by: cad84
Category:

less

Transcript and Presenter's Notes

Title: Lecture%20I%20-%20Polymorphism


1
Lecture I - Polymorphism
  • Unit I1 - Introduction to Polymorphism

2
Polymorphism
  • Recall that method invocation is virtual
  • The actual method called depends on the runtime
    type
  • Thus the behavior obtained using x.m() takes a
    different form according to the subtype that x
    has.
  • This can be used for customizing the behavior of
    a piece of code that deals with objects of the
    super-class type without modifying the code
    itself.

3
Factoring out variations to the sub-classes
Kid k // k Boy or Girl if (k instanceOf
Boy) // draw in blue else // draw in
red // more unisex code
Kid
Boy
Girl
Kid k // k Boy or Girl Color c
k.getColor() // all unisex code
4
Overriding getColor()
class Kid // public Color getColor()
return Color.purple class Boy extends
Kid public Color getColor() return
Color.blue class Girl extends Kid
public Color getColor() return Color.red

5
Documenting getColor()
/ Returns the color in which to graphically
represent the kid. Default is purple.
/ class Kid // public Color getColor()
return Color.purple
6
Abstract Classes
  • Sometimes we dont want to give any
    implementation for a super-class method, but
    rather force all subclasses to provide an
    implementation.
  • We need to make the definition of the method in
    the super-class as to allow polymorphism in code
    that deals with instances of the super-class
    compile-time type.
  • We can define the method as being abstract, and
    thus force all subclasses to implement it.
  • In this case there can be no instances of the
    super-class type (but only of subclass of it),
    and the super-class must be defined as abstract.

7
Abstract version of Kid
abstract class Kid // abstract public
Color getColor() class Boy extends Kid
public Color getColor() return Color.blue
class Girl extends Kid public Color
getColor() return Color.red
8
Interfaces
  • The most extreme form of an abstract class is one
    that only has obligations
  • No fields
  • All methods are abstract
  • This case is very important as it simply
    formalizes an interface.
  • Java has a special syntax for this called
    Interface.
  • A class can only extend a single direct
    super-class, but can implement any number of
    Interfaces.

9
Lecture I - Polymorphism
  • Unit I2 - Heterogeneous Collections

10
Lesson or Unit Topic or Objective
Using Heterogeneous Collections
11
Heterogeneous Collections
  • When we have a collection of objects of an object
    type, some of the objects in the collection may
    have a subclass run-time type.
  • Thus such a collection will have heterogeneous
    types.
  • This may be used just to hold the objects
    together, or also may apply polymorphic behavior
  • When objects are taken out of the collection,
    they need to be narrowed into the subtype you
    want to work with

12
SwitchPanel Heterogeneous Collection
  • Suppose, for example, that we want a class
    SwitchPanel that represents a panel of switches.
    Some of the switches in the panel are simple
    switches and some are adjustable switches.
  • Suppose also that weve added the method
    getConsumption() in class Switch that returns the
    electrical consumption of the switch (which is 0
    if the switch is off and maxPower if the switch
    is on)
  • This method was overridden in class
    AdjustableSwitch (the consumption is 0 if the
    switch is off, or level maxPower / 100 if it is
    on).

13
getConsumption()
public class Switch // ... same
implementation as before public double
getConsumption() return isOn() ? maxPower
0 public class AdjustableSwitch extends
Switch // ... same implementation as before
public double getConsumption() return
super.getConsumption() level / 100
14
Switch Panel design idea
  • When implementing our SwitchPanel class, we would
    like to store switches of both kinds in a single
    array, so we can easily write code that operates
    on both kinds of switches.
  • For example, suppose we want to implement a
    method getTotalConsumption() in class SwitchPanel
    that will compute the total electrical
    consumption of all the switches in the panel,
    whether they are adjustable switches or regular
    switches.

15
SwitchPanel
public class SwitchPanel private Switch
switches private int numSwitches public
SwitchPanel(int maxSwitches) switches new
SwitchmaxSwitches numSwitches 0
public void addSwitch(Switch s)
switchesnumSwitches s public double
getTotalConsumption() double total 0.0
for (int i 0 i lt switches.length i)
total switchesi.getConsumption()
return total
16
Heterogeneous Collections in the Java API
  • Collection classes in the Java API contain
    arbitrary Objects.
  • One of the simplest is java.util.Vector.
  • A vector is an ordered collection of objects.
  • You may add or remove objects from the vector at
    any position
  • The size of a Vector grows and shrinks as needed
    to accommodate adding and removing items after
    the Vector has been created.

17
Animals
class Cat public String toString() return
meaw class Dog public String
toString() return roff class Mouse
public String toString() return squeak
public String complain() return Ouch
18
Vector of Animals
class AnimalSounds public static void
main(String args) Vector v new
Vector() v.addElement(new Cat())
v.addElement(new Mouse()) v.addElement(new
Dog()) for (int i 0 i lt v.size() i)
System.out.println(v.elementAt(i)) if
(v.elementAt(i) instanceof Mouse) Mouse
m (Mouse) v.elementAt(i)
System.out.println(m.complain())

19
Lecture I - Polymorphism
  • Unit I3 - Abstract Classes

20
Paint Brush Application
Paint Brush
Paint Brush application
21
Paint-brush application design
  • Consider the design of a paint-brush application
  • We want to represent the drawing as a collection
    of objects, each represents a certain figure.
  • We want to represent each type of figure with a
    suitable class. Objects of these classes will
    know how to draw themselves.
  • The classes have common properties (location,
    size, color, ...) and common behaviors (moveTo(),
    resize(), ...).
  • We want to have a common super-class for all
    these classes that will define all the common
    properties and behaviors.

22
A class hierarchy for Figures
moveTo(x,y) moveBy(dx,dy) resize(factor) setLineCo
lor(color)...
Figure
Ellipse
Rectangle
draw() contains(x,y)
draw() contains(x,y)
23
Figure class
/ A geometrical figure. A Figure has a
location and size it can draw itself on the
screen ... / public class Figure // The
top-left corner of the rectangular bounding box
// of the figure protected int x,y // The
dimensions of the figure (of the bounding box
// of the figure) protected int width,
height // The color of the border of the
figure private Color lineColor // ... other
properties
24
Figure -- methods
public Figure(int x, int y, int width, int
height) this.x x this.y y
this.width width this.height height
public Color getLineColor() return
lineColor public void moveTo(int x, int y)
this.x x this.y y public void
moveBy(int dx, int dy) moveTo(xdx, ydy)
25
Rectangle
public class Rectangle extends Figure public
Rectangle(int x, int y, int width, int height)
super(x, y, width, height) public void
draw() Turtle painter new Turtle()
painter.setLocation(x,y) painter.setAngle(0)
painter.tailDown() painter.moveForwards(widt
h) painter.turnRight(90)
painter.moveForwards(height)
painter.turnRight(90) painter.moveForwards(wi
dth) painter.turnRight(90)
painter.moveForwards(height)
painter.hide()
26
Abstract classes
  • Weve used class Figure to ease our design. It is
    also correct from the point of view of our
    abstraction
  • However, note that we will never want to create
    instances of class Figure, only of subclasses of
    this class!
  • To denote this, we define the class Figure as an
    abstract class.

27
Figure as an abstract class
/ A geometrical figure. A Figure has a
location and size it can draw itself on the
screen ... / public abstract class Figure
// The top-left corner of the rectangular area
that // contains the figure protected int
x,y // ...
  • Now, we cannot create instances of class Figure,
    only instances of subclasses of Figure which are
    not definedas abstract.

28
The draw() method
  • What are the benefits of defining a class
    abstract?
  • Note that the draw() method appears in the
    interface of all subclasses of class Figure, but
    is implemented differently in each one of them.
  • If we have defined this method in class Figure,
    it was to say that every figure can draw itself.
    We would then override this method in every
    specific subclass and could draw an heterogeneous
    collection of figures with a single loop.

29
Using Figures
public class PaintBrushPicture private Vector
figures public PaintBrushPicture()
figures new Vector() public void
addFigure(Figure figure) figures.addElement(
figure) public void drawPicture()
for (int i0 iltfigures.size() i)
((Figure)figures.elementAt(i)).draw()
// ...
30
Abstract methods
  • But how should we define the method draw() in
    class Figure? There is no meaning for drawing an
    abstract figure!
  • We can make a workaround and write an empty
    implementation for draw() in Figure. This is NOT
    clean! It is a patch! Moreover what about methods
    like contains() ?
  • The catch is that we do not have to implement
    this method, because no one can create instances
    of class Figure! Instead we declare the method as
    abstract and omit its body.

31
Figure abstract methods
/ A geometrical figure. ... / public
abstract class Figure //... state variables
as before / Draws this figure. /
public abstract void draw() / Checks
whether a given point is in the
interior of this figure. / public abstract
boolean contains(int x, int y)
32
ChessPiece class Hierarchy
moveTo(x,y) moveBy(dx,dy) getLocation() getPossibl
eMoves()...
ChessPiece
. . .
Pawn
Rook
Knight
getPossibleMoves()
getPossibleMoves()
getPossibleMoves()

33
Electronic Gate class hierarchy
getNumberOfInputs() getInputVoltage(i) setInputVol
tage(i) getOutputVoltage() process()
ElectronicGate
. . .
AndGate
OrGate
NotGate
process()
process()
process()

34
Lecture I - Polymorphism
  • Unit I4 - Interfaces

35
Interfaces
  • An Interface is a totally abstract class
  • No fields
  • All methods are abstract
  • It thus defines an interface that must be
    implemented by each one of its sub-classes
  • In Java, a class may implement many interfaces,
    even though it may extend only a single
    super-class
  • When should interfaces be used for?
  • What we view in our abstraction as a set of
    obligations
  • Whenever we would need multiple inheritance
    otherwise

36
Movable Shape
public interface Movable public Point
getCenter() public void move(float deltaX,
float deltaY)
37
Point
public class Point implements Movable
private float x, y public Point(float x,float
y) this.x xthis.y y public float
getX() return x public float getY()
return y public Point getCenter() return
this public void move(float deltaX, float
deltaY) x deltaX y deltaY
38
Rectangle
public class Rectangle implements Movable
private float top, bottom, left, right public
Rectangle(float t,float b,float l,float r)
top t bottom b left l right r
public float getCenter() return
new Point((topbottom)/2,(leftright)/2 )
public void move(float deltaX, float deltaY)
top deltaY bottom deltaY left
deltaX right deltaX
39
Circle
public class Circle implements Movable
private Point center private float radius
public Circle(Point p, float r) center
pradius r public float getCenter()
return center public float getRadius()
return radius public void move(float
deltaX, float deltaY) center.move(deltaX,
deltaY)
40
MovingExample
public class MovingExample public static void
main(String args) Rectangle r new
Rectangle(10.0, 20.0, 30.0, 40.0)
moveDownToZone(r) Circle c new Circle(new
Point(10.0, 20.0) , 5.0) moveDownToZone(c)
public static void moveDownToZone(Movable
s) final float zoneTop 200.0 final
float step 10.0 while ( s.getCenter().getY(
) lt zoneTop ) s.move(0.0, step)
41
Paint Brush Application II
  • Recall the paint-brush application example.
    Supposewe want now to be able to paint also
    pixels and lines.

Paint Brush
Paint Brush application
42
The need for the Drawable Interface
Drawable
Object
Point
Line
Figure
Polygon
Rectangle
Pixel
Ellipse

43
The Drawable Interface
Drawable view
getLocation() moveTo() moveBy() draw()
toString() ... getEdgeSize() setEdgeSize()
Figure view
Rectagle
Rectangle view
Object view
44
Drawable
/ An interface for classes whose instances
know how to draw themselves on a graphical
window. / public interface Drawable /
Draws this object. / public void
draw()
45
Pixel
/ Represents a pixel on a graphical area.
/ public class Pixel extends Point implements
Drawable ... / Draws this
pixel on the screen. / public void draw()
... ...
46
Figure implementing Drawable
/ A geometrical figure. A Figure has a
location and size it can draw itself on the
screen ... / public abstract class Figure
implements Drawable // As before ...
// No need to redefine draw()
47
Using Drawable
/ A picture made of geometrical figures.
/ public class PaintBrushPicture // The
elements (figures) that compose this picture
private Drawable elements ... /
Draws this picture. / public void drawAll()
for (int i0 ilt elements.size() i)
elementsi.draw()
48
Implementing multiple interfaces
/ A geometrical figure. A Figure has a
location and size, it can draw itself on the
screen ... / public abstract class Figure
implements Drawable, Moveable ...
public void move(int deltaX, int deltaY)
this.x deltaX this.y deltaY
...
49
Fighters
public interface Fighter public void
hit() public class KungFuFighter implements
Fighter public void hit()
System.out.print(trach! ) public class
Boxer implements Fighter private boolean
nextPunchLeft public Boxer(boolean
leftHanded)nextPunchLeftleftHanded
public void hit() System.out.print(nextPnchLe
ft ? left pow! right pow! )
nextPunchLeft !nextPunchLeft
50
FightingArmy
public class FightingArmy public static void
main(String args) Fighter soldiers
new Fighter10 for ( int j 0 j lt 10
j ) if ( Math.random() gt 0.5 )
soldiersj new Boxer(true) else
soldiersj new KungFuFighter() for ( int
j 0 j lt 10 j ) System.out.print(S
oldier j ) for (int k 0 k lt 5
k) soldiersj.hit()
System.out.println()

51
Different Implementations
public interface SetOfInts public void
insert(int x) public boolean contains(int
x) public class MySetOfInts implements
SetOfInts // Very Easy Implementation public
class IBMSetOfInts implements SetOfInts //
Very Good Implementation public class
MyProgram SetOfInts s new
MySetOfInts(30)//new IBMSetOfInts()
s.insert(7) s.contains(15)
52
Comparable
public interface Comparable boolean
gt(Comparable other) public class Date
implements Comparable private int year,
month, day public Date(y,m,d) yeary
monthm dayd public String toString()
return d/m/y public boolean
gt(Comparable other) Date d (Date)
other if (year ! d.year) return year gt
d.year if (month ! d.month) return month gt
d.month return day gt d.day
53
Generic Sorter
public class Sorter public static void
selectionSort (Comparable a) for (int j
0 j lt a.length-1 j) min j
for (int k j1 k lt a.length k )
if ( amin.gt(ak) ) min k
if (min ! j) Comparable temp
amin amin aj
aj temp

54
Using the Generic Sorter
public class DateSortTest public static void
main (String args) Date dates new
Date4 dates0 new Date(1947, 11, 29)
dates1 new Date(2000, 1, 1) dates2
new Date(1967, 6, 6) dates3 new
Date(2000, 12, 19) Sorter.selectionSort(dates
) for ( int j 0 j lt 4 j )
System.out.println(datesj)
55
Lecture I - Polymorphism
  • Unit I5 - Enumeration Example

56
Enumerations
  • In many cases we need to go over all items in a
    collection
  • Values in a linked list
  • Entries in a dictionary
  • Vertices in a graph
  • All prime numbers
  • A class that allows going over a set of items is
    called an iterator or an enumeration
  • The basic operation supported is to get the next
    item
  • This is usually formalized as an interface that
    is implemented by each class that provides an
    enumeration of a particular collection type.
  • This is a classic design pattern

57
IntEnumeration
/ An enumeration of Integers.The following
code goes over all elements of an enumeration
E that implements this interface for( E e
new E() e.hasItem() e.advance() )
int num e.getItem() / public
interface IntEnumeration / Is there a
current item / boolean hasItem() /
Return the current item. May only be called if
hasItem(). / int getItem() / Advance to
the next item.May only be called if hasItem().
/ void advance()
58
NaturalsTo100
public class NaturalsTo100 implements
IntEnumeration private int current
public NaturalsTo100() current 1 public
boolean hasItem() return current lt 100
public void advance() current public
int getItem() return current
59
ArrayEnumeration
public class ArrayEnumeration implements
IntEnumeration private int elements
private int n public ArrayEnumeration(int
a) elements a n 0 public boolean
hasItem() return n lt elements.length
public int getItem() return elementsn
public void advance() n
60
BitsEnumeration
public class BitEnumeration implements
IntEnumeration private int n public
BitEnumeration(int n) this.n n public
boolean hasItem() return ngt0 public void
advance() n / 2 public int getItem()
return n 2
61
EnumerationDemo
public class EnumerationDemo public static
void main(String args) IntEnumeration e1
new NaturalsTo100() IntEnumeration e2
new ArrayEnumeration( 89, 67, 99, 84 )
IntEnumeration e3 new BitEnumeration( 123456
) System.out.println(The sum of the first
100 numers is sum(e1)) System.out.println(
The sum of your grades is sum(e2))
System.out.println( The number of 1 bits in
123456 is sum(e3)) private static int
sum(IntEnumeration e) for(int s 0
e.hasItem() e.advance()) s
e.getItem() return s
62
SigmaEnumeration
public class SigmaEnumeration implements
IntEnumeration private int s private
IntEnumeration e public SigmaEnumeration(IntEn
umeration e) s 0this.e e public
boolean hasItem() return e.hasItem()
public int getItem() return s e.getItem()
public void advance() s e.getItem()
e.advance() --------------------------------
-------------------------- IntEnumeration e
new SigmaEnumeration( new NaturalsTo100()
) while(e.hasItem()) System.out.println(e.getI
tem())e.advance
63
Filters
interface IntFilter boolean accept(int
x) public class DoesntDivideFilter implements
IntFilter private int divisor public
DoesntDivideFilter(int divisor)
this.divisor divisor public boolean
accept(int x) return (x divisor) ! 0

64
FilteredEnumeration
public class FilteredEnumeration implements
IntEnumeration private IntEnumeration e
private IntFilter f public FilteredEnumeration
(IntEnumeration e, IntFilter f) this.e e
this.f f while (e.hasItem()
!f.accept(e.getItem)) e.advance() public
boolean hasItem() return e.hasItem()
public int getItem() return e.getItem()
public void advance() do e.advance()
while(e.hasItem()!f.accept(e.getItem()))

65
Prime Numbers
public class Sieve public static void
main(String args) IntEnumeration e new
NaturalsTo100() IntFilter f
e.advance() // throw away 1 while
(e.hasItem()) int prime e.getItem()
System.out.println(prime) f new
DoesntDivideFilter(prime) e new
FilteredEnumeration(e, f)
66
Lecture I - Polymorphism
Write a Comment
User Comments (0)
About PowerShow.com