+ All Categories
Home > Documents > Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Date post: 17-Dec-2015
Category:
Upload: philip-riley
View: 221 times
Download: 1 times
Share this document with a friend
66
Slide 1 of Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism
Transcript
Page 1: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 1 of 66.Lecture I

Lecture I - Polymorphism

Unit I1 - Introduction to Polymorphism

Page 2: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 2 of 66.Lecture I

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.

Page 3: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 3 of 66.Lecture I

Factoring out variations to the sub-classesKid k;… // k = Boy or Girlif (k instanceOf Boy) … // draw in blueelse … // draw in red… // more unisex code

Kid k;… // k = Boy or GirlColor c = k.getColor();… // all unisex code

KidKid

BoyBoy GirlGirl

Page 4: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 4 of 66.Lecture I

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; }}

Page 5: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 5 of 66.Lecture I

Documenting getColor()

/** * Returns the color in which to graphically * represent the kid. Default is purple. */

class Kid { // … public Color getColor() { return Color.purple; }}

Page 6: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 6 of 66.Lecture I

Abstract Classes

• Sometimes we don’t 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.

Page 7: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 7 of 66.Lecture I

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; }}

Page 8: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 8 of 66.Lecture I

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.

Page 9: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 9 of 66.Lecture I

Lecture I - Polymorphism

Unit I2 - Heterogeneous Collections

Page 10: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 10 of 66.Lecture I

Lesson or Unit Topic or Objective

Using Heterogeneous Collections

Page 11: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 11 of 66.Lecture I

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

Page 12: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 12 of 66.Lecture I

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 we’ve 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).

Page 13: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 13 of 66.Lecture I

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; }}

Page 14: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 14 of 66.Lecture I

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.

Page 15: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 15 of 66.Lecture I

SwitchPanel

public class SwitchPanel { private Switch[] switches; private int numSwitches;

public SwitchPanel(int maxSwitches) { switches = new Switch[maxSwitches]; numSwitches = 0; } public void addSwitch(Switch s){ switches[numSwitches++] = s; } public double getTotalConsumption() { double total = 0.0; for (int i = 0; i < switches.length; i++) total += switches[i].getConsumption(); return total; }}

Page 16: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 16 of 66.Lecture I

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.

Page 17: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 17 of 66.Lecture I

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” ; }}

Page 18: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 18 of 66.Lecture I

Vector of Animalsclass 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 < 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()); } } }}

Page 19: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 19 of 66.Lecture I

Lecture I - Polymorphism

Unit I3 - Abstract Classes

Page 20: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 20 of 66.Lecture I

Paint Brush Application

Paint Brush

Paint Brush application

Page 21: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 21 of 66.Lecture I

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.

Page 22: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 22 of 66.Lecture I

Figure

Rectangle Ellipse

draw()

contains(x,y)draw()

contains(x,y)

moveTo(x,y)

moveBy(dx,dy)

resize(factor)

setLineColor(color)...

A class hierarchy for Figures

Page 23: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 23 of 66.Lecture I

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

Page 24: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 24 of 66.Lecture I

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(x+dx, y+dy);}

Page 25: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 25 of 66.Lecture I

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(width); painter.turnRight(90); painter.moveForwards(height); painter.turnRight(90); painter.moveForwards(width); painter.turnRight(90); painter.moveForwards(height); painter.hide(); }}

Page 26: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 26 of 66.Lecture I

Abstract classes

• We’ve 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.

Page 27: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 27 of 66.Lecture I

Figure as an abstract class

Now, we cannot create instances of class Figure, only instances of subclasses of Figure which are not definedas abstract.

/** * 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;

// ...

Page 28: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 28 of 66.Lecture I

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.

Page 29: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 29 of 66.Lecture I

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 i=0; i<figures.size(); i++) { ((Figure)figures.elementAt(i)).draw(); } } // ...}

Page 30: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 30 of 66.Lecture I

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.

Page 31: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 31 of 66.Lecture I

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

Page 32: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 32 of 66.Lecture I

ChessPiece

Pawn Rook

moveTo(x,y)

moveBy(dx,dy)

getLocation()

getPossibleMoves()...

getPossibleMoves()getPossibleMoves()getPossibleMoves()

Knight . . .

ChessPiece class Hierarchy

Page 33: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 33 of 66.Lecture I

ElectronicGate

AndGate OrGate

getNumberOfInputs()

getInputVoltage(i)

setInputVoltage(i)

getOutputVoltage()

process()

process()process() process()

NotGate . . .

Electronic Gate class hierarchy

Page 34: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 34 of 66.Lecture I

Lecture I - Polymorphism

Unit I4 - Interfaces

Page 35: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 35 of 66.Lecture I

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

Page 36: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 36 of 66.Lecture I

public interface Movable { public Point getCenter(); public void move(float deltaX, float deltaY);}

Movable Shape

Page 37: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 37 of 66.Lecture I

public class Point implements Movable { private float x, y;

public Point(float x,float y) { this.x = x;this.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; }}

Point

Page 38: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 38 of 66.Lecture I

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((top+bottom)/2,(left+right)/2 ); } public void move(float deltaX, float deltaY) { top += deltaY ; bottom += deltaY ; left += deltaX ; right += deltaX ; }}

Rectangle

Page 39: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 39 of 66.Lecture I

public class Circle implements Movable { private Point center; private float radius;

public Circle(Point p, float r) {center = p;radius = r}

public float getCenter() { return center; }

public float getRadius() { return radius; }

public void move(float deltaX, float deltaY) { center.move(deltaX, deltaY) }}

Circle

Page 40: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 40 of 66.Lecture I

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() < zoneTop ) s.move(0.0, step); }}

MovingExample

Page 41: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 41 of 66.Lecture I

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

Page 42: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 42 of 66.Lecture I

Object

Figure Line Point

Rectangle Ellipse Polygon

Drawable

Pixel

The need for the Drawable Interface

Page 43: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 43 of 66.Lecture I

The Drawable Interface

Rectagle

getLocation()

moveTo()

moveBy()

draw()

toString()

...

getEdgeSize()

setEdgeSize()

Obj

ect v

iew

Fig

ure

view

Rec

tang

le v

iew

Drawable view

Page 44: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 44 of 66.Lecture I

/** * An interface for classes whose instances know how * to draw themselves on a graphical window. */public interface Drawable {

/** * Draws this object. */ public void draw();

}

Drawable

Page 45: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 45 of 66.Lecture I

/** * Represents a pixel on a graphical area. */public class Pixel extends Point implements Drawable { ...

/** * Draws this pixel on the screen. */ public void draw() { ... }

...

}

Pixel

Page 46: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 46 of 66.Lecture I

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

Page 47: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 47 of 66.Lecture I

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 i=0; i< elements.size(); i++) elements[i].draw(); }

Page 48: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 48 of 66.Lecture I

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; }

...

Page 49: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 49 of 66.Lecture I

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){nextPunchLeft=leftHanded;} public void hit(){ System.out.print(nextPnchLeft ? “left pow! ” : “right pow! ”); nextPunchLeft = !nextPunchLeft; }}

Fighters

Page 50: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 50 of 66.Lecture I

public class FightingArmy { public static void main(String[] args) { Fighter[] soldiers = new Fighter[10]; for ( int j = 0 ; j < 10 ; j++ ) if ( Math.random() > 0.5 ) soldiers[j] = new Boxer(true); else soldiers[j] = new KungFuFighter(); for ( int j = 0 ; j < 10 ; j++ ) { System.out.print(“Soldier ” + j + “:”); for (int k = 0 ; k < 5 ; k++) soldiers[j].hit(); System.out.println(); } } }

FightingArmy

Page 51: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 51 of 66.Lecture I

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) …}

Different Implementations

Page 52: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 52 of 66.Lecture I

public interface Comparable { boolean gt(Comparable other);}

public class Date implements Comparable { private int year, month, day; public Date(y,m,d) { year=y ; month=m ; day=d; } public String toString() { return d+“/”+m+“/”+y; } public boolean gt(Comparable other) { Date d = (Date) other; if (year != d.year) return year > d.year; if (month != d.month) return month > d.month; return day > d.day; }}

Comparable

Page 53: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 53 of 66.Lecture I

public class Sorter { public static void selectionSort (Comparable[] a) { for (int j = 0 ; j < a.length-1 ; j++) { min = j; for (int k = j+1 ; k < a.length ; k++ ) if ( a[min].gt(a[k]) ) min = k; if (min != j) { Comparable temp = a[min] ; a[min] = a[j] ; a[j] = temp; } } } }}

Generic Sorter

Page 54: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 54 of 66.Lecture I

public class DateSortTest{ public static void main (String[] args) { Date[] dates = new Date[4]; dates[0] = new Date(1947, 11, 29); dates[1] = new Date(2000, 1, 1); dates[2] = new Date(1967, 6, 6); dates[3] = new Date(2000, 12, 19); Sorter.selectionSort(dates); for ( int j =0 ; j < 4 ; j++ ) System.out.println(dates[j]); }}

Using the Generic Sorter

Page 55: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 55 of 66.Lecture I

Lecture I - Polymorphism

Unit I5 - Enumeration Example

Page 56: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 56 of 66.Lecture I

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

Page 57: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 57 of 66.Lecture I

/** *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();}

IntEnumeration

Page 58: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 58 of 66.Lecture I

public class NaturalsTo100 implements IntEnumeration{ private int current;

public NaturalsTo100() { current = 1; } public boolean hasItem() { return current <= 100; } public void advance() { current++ ; } public int getItem() { return current; }}

NaturalsTo100

Page 59: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 59 of 66.Lecture I

public class ArrayEnumeration implements IntEnumeration{ private int[] elements; private int n;

public ArrayEnumeration(int[] a) {elements = a ;n = 0; } public boolean hasItem() { return n < elements.length; } public int getItem() { return elements[n]; } public void advance() { n++ ; }}

ArrayEnumeration

Page 60: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 60 of 66.Lecture I

public class BitEnumeration implements IntEnumeration{ private int n;

public BitEnumeration(int n) { this.n = n; } public boolean hasItem() { return n>0 ; } public void advance() { n /= 2 ; } public int getItem() { return n % 2; }}

BitsEnumeration

Page 61: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 61 of 66.Lecture I

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; }}

EnumerationDemo

Page 62: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 62 of 66.Lecture I

public class SigmaEnumeration implements IntEnumeration { private int s; private IntEnumeration e;

public SigmaEnumeration(IntEnumeration e){ s = 0;this.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.getItem());e.advance;}

SigmaEnumeration

Page 63: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 63 of 66.Lecture I

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 ; }}

Filters

Page 64: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 64 of 66.Lecture I

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

FilteredEnumeration

Page 65: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 65 of 66.Lecture I

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); } }}

Prime Numbers

Page 66: Slide 1 of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism.

Slide 66 of 66.Lecture I

Lecture I - Polymorphism


Recommended