UPLOAD

    4.3K

    lecture 1-java polymorphism

    Published: July 19, 2018

    Java polymorphism

    Comments

    lecture 1-java polymorphism

    • 1. Lecture I - Polymorphism Slide ‹#› of 66. Lecture I Lecture I - Polymorphism Unit I1 - Introduction to Polymorphism
    • 2. Polymorphism Slide ‹#› 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.
    • 3. Factoring out variations to the sub-classes Slide ‹#› of 66. Lecture I 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 k; … // k = Boy or Girl Color c = k.getColor(); … // all unisex code Kid Boy Girl
    • 4. Overriding getColor() Slide ‹#› 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; } }
    • 5. Documenting getColor() Slide ‹#› 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; } }
    • 6. Abstract Classes Slide ‹#› 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.
    • 7. Abstract version of Kid Slide ‹#› 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; } }
    • 8. Interfaces Slide ‹#› 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.
    • 9. Lecture I - Polymorphism Slide ‹#› of 66. Lecture I Lecture I - Polymorphism Unit I2 - Heterogeneous Collections
    • 10. Lesson or Unit Topic or Objective Slide ‹#› of 66. Lecture I Lesson or Unit Topic or Objective Using Heterogeneous Collections
    • 11. Heterogeneous Collections Slide ‹#› 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
    • 12. SwitchPanel Heterogeneous Collection Slide ‹#› 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).
    • 13. getConsumption() Slide ‹#› 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; } }
    • 14. Switch Panel – design idea Slide ‹#› 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.
    • 15. SwitchPanel Slide ‹#› 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; } }
    • 16. Heterogeneous Collections in the Java API Slide ‹#› 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.
    • 17. Animals Slide ‹#› 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” ; } }
    • 18. Vector of Animals Slide ‹#› of 66. Lecture I 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 < 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 Slide ‹#› of 66. Lecture I Lecture I - Polymorphism Unit I3 - Abstract Classes
    • 20. Paint Brush Application Slide ‹#› of 66. Lecture I Paint Brush Application Paint Brush Paint Brush application
    • 21. Paint-brush application design Slide ‹#› 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.
    • 22. A class hierarchy for Figures Slide ‹#› 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
    • 23. Figure class Slide ‹#› 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
    • 24. Figure -- methods Slide ‹#› 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); }
    • 25. Rectangle Slide ‹#› 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(); } }
    • 26. Abstract classes Slide ‹#› 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.
    • 27. Figure as an abstract class Slide ‹#› 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 defined as 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; // ...
    • 28. The draw() method Slide ‹#› 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.
    • 29. Using Figures Slide ‹#› 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
    • 30. Abstract methods Slide ‹#› 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.
    • 31. Figure – abstract methods Slide ‹#› 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);
    • 32. ChessPiece class Hierarchy Slide ‹#› of 66. Lecture I ChessPiece Pawn Rook moveTo(x,y) moveBy(dx,dy) getLocation() getPossibleMoves() ... getPossibleMoves() getPossibleMoves() getPossibleMoves() Knight . . . ChessPiece class Hierarchy
    • 33. Electronic Gate class hierarchy Slide ‹#› of 66. Lecture I ElectronicGate AndGate OrGate getNumberOfInputs() getInputVoltage(i) setInputVoltage(i) getOutputVoltage() process() process() process() process() NotGate . . . Electronic Gate class hierarchy
    • 34. Lecture I - Polymorphism Slide ‹#› of 66. Lecture I Lecture I - Polymorphism Unit I4 - Interfaces
    • 35. Interfaces Slide ‹#› 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
    • 36. Movable Shape Slide ‹#› of 66. Lecture I public interface Movable { public Point getCenter(); public void move(float deltaX, float deltaY); } Movable Shape
    • 37. Point Slide ‹#› 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
    • 38. Rectangle Slide ‹#› 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
    • 39. Circle Slide ‹#› 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
    • 40. MovingExample Slide ‹#› 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
    • 41. Paint Brush Application II Slide ‹#› of 66. Lecture I Paint Brush Application II Recall the paint-brush application example. Suppose we want now to be able to paint also pixels and lines. Paint Brush Paint Brush application
    • 42. The need for the Drawable Interface Slide ‹#› of 66. Lecture I Object Figure Line Point Rectangle Ellipse Polygon Drawable Pixel The need for the Drawable Interface
    • 43. The Drawable Interface Slide ‹#› of 66. Lecture I The Drawable Interface Rectagle getLocation() moveTo() moveBy() draw() toString() ... getEdgeSize() setEdgeSize() Object view Figure view Rectangle view Drawable view
    • 44. Drawable Slide ‹#› 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
    • 45. Pixel Slide ‹#› 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
    • 46. Figure implementing Drawable Slide ‹#› 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()
    • 47. Using Drawable Slide ‹#› 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(); }
    • 48. Implementing multiple interfaces Slide ‹#› 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; } ...
    • 49. Fighters Slide ‹#› 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
    • 50. FightingArmy Slide ‹#› 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
    • 51. Different Implementations Slide ‹#› 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
    • 52. Comparable Slide ‹#› 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
    • 53. Generic Sorter Slide ‹#› 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
    • 54. Using the Generic Sorter Slide ‹#› 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
    • 55. Lecture I - Polymorphism Slide ‹#› of 66. Lecture I Lecture I - Polymorphism Unit I5 - Enumeration Example
    • 56. Enumerations Slide ‹#› 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
    • 57. IntEnumeration Slide ‹#› 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
    • 58. NaturalsTo100 Slide ‹#› 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
    • 59. ArrayEnumeration Slide ‹#› 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
    • 60. BitsEnumeration Slide ‹#› 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
    • 61. EnumerationDemo Slide ‹#› 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
    • 62. SigmaEnumeration Slide ‹#› 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
    • 63. Filters Slide ‹#› 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
    • 64. FilteredEnumeration Slide ‹#› 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
    • 65. Prime Numbers Slide ‹#› 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
    • 66. Lecture I - Polymorphism Slide ‹#› of 66. Lecture I Lecture I - Polymorphism