Polymorphism
Polymorphism
Object-oriented programming Inf1 :: 2008
Object-oriented programming Polymorphism
Polymorphism Object-oriented programming Inf1 :: 2008 - - PowerPoint PPT Presentation
Polymorphism Polymorphism Object-oriented programming Inf1 :: 2008 Object-oriented programming Polymorphism Polymorphism Overview Polymorphism is a concept that allows the programmer to program abstractly Objects of a subclass can be treated
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
point coordinates x = 50, y = 50 circle coordinates x = 60, y = 60 anotherPoint coordinates x = 60, y = 60
public class HierarchyRelationshipTest { public static void main (String [] args) { Point point = new Point(50, 50); Circle circle = new Circle(60, 60, 6.0); System.out.println("point coordinates x = " + point.getX() + ", y = " + point.getY()); System.out.println("circle coordinates x = " + circle.getX() + ", y = " + circle.getY()); Point anotherPoint = circle; System.out.println("anotherPoint coordinates x = " + anotherPoint.getX() + ", y = " + anotherPoint.getY()); System.exit(0); } } Object-oriented programming Polymorphism
Polymorphism
assign superclass reference to subclass variable
HierarchyRelationshipTest2.java:12: incompatible types found : Point required: Circle circle = point; ^ 1 error public class HierarchyRelationshipTest2 { public static void main (String [] args) { Point point = new Point(50, 50); Circle circle; circle = point; } }
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
no problem invoking superclass behaviour using a superclass reference this is wrong invoking subclass behaviour using a superclass reference
HierarchyRelationshipTest3.java:14: cannot resolve symbol symbol : method getRadius () location: class Point double radius = point.getRadius(); ^ HierarchyRelationshipTest3.java:15: cannot resolve symbol symbol : method setRadius (double) location: class Point point.setRadius( 33.33 ); ^ HierarchyRelationshipTest3.java:16: cannot resolve symbol symbol : method getDiameter () location: class Point double diameter = point.getDiameter(); ^ HierarchyRelationshipTest3.java:17: cannot resolve symbol symbol : method getCircumference () location: class Point double circumference = point.getCircumference(); ^ HierarchyRelationshipTest3.java:18: cannot resolve symbol symbol : method getArea () location: class Point double area = point.getArea(); ^ 5 errors public class HierarchyRelationshipTest3 { public static void main (String[] args) { Point point; Circle circle = new Circle(120, 89, 2.7); point = circle; int x = point.getX(); int y = point.getY(); point.setX(10); point.setY(20); double radius = point.getRadius(); point.setRadius(33.33); double diameter = point.getDiameter(); double circumference = point.getCircumference(); double area = point.getArea(); } }
Object-oriented programming Polymorphism
Polymorphism
public class HierarchyRelationshipTest3 { public static void main (String[] args) { Point point; Circle circle = new Circle(120, 89, 2.7); point = circle; int x = point.getX(); int y = point.getY(); point.setX(10); point.setY(20); double radius = ((Circle) point).getRadius(); ((Circle) point).setRadius(33.33); double diameter = ((Circle) point).getDiameter(); double circumference = ((Circle) point).getCircumference(); double area = ((Circle) point).getArea(); } }
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
+ getX() : Integer + getY() : Integer + setX(Integer) : void + setY(Integer) : void
Point + getRadius() : Real + setRadius(Real) : void + getDiameter() : Real + getCircumference() : Real
Circle + getHeight() : Real + setHeight(Real) : void
Cylinder + getArea() : Real (= 0.0) + getVolume() : Real (= 0.0) + getName() : String + draw() : void Shape abstract class: getArea() and getVolume() have default implementations; getName() and draw() are subclass-specific, so are abstract methods concrete classes: extend abstract class with their own behaviour; must override abstract methods
Object-oriented programming Polymorphism
Polymorphism
public abstract class Shape extends Object { public double getArea() { return 0.0; } public double getVolume() { return 0.0; } public abstract String getName(); public abstract void draw(); } Object-oriented programming Polymorphism
Polymorphism
public class Point extends Shape { private int x; private int y; public Point() {} public Point (int x, int y) { this.x = x; this.y = y; } public void setX (int x) { this.x = x; } public int getX () { return x; } public void setY (int y) { this.y = y; } public int getY () { return y; } public String getName () { return "Point"; } public void draw () { // drawing code goes here } } Object-oriented programming Polymorphism
Polymorphism
subclass-specific code and behaviour no need to override getVolume(); Shape‘s implementation is still OK abstract methods are
Circle
should be redefined
public class Circle extends Point { private double radius; public Circle () {} public Circle (int x, int y, double r) { super(x, y); setRadius(r); } public void setRadius (double r) { radius = (r < 0.0 ? 0.0 : r); } public double getRadius () { return radius; } public double getDiameter () { return 2 * getRadius(); } public double getCircumference () { return Math.PI * getDiameter(); } public double getArea () { return Math.PI * getRadius() * getRadius(); } public String getName () { return "Circle"; } public void draw () { // code to draw a circle goes here } }
Object-oriented programming Polymorphism
Polymorphism
subclass-specific behaviour
getArea() and getVolume(); existing definitions are wrong abstract methods
Cylinder
public class Cylinder extends Circle { private double height; public Cylinder () {} public Cylinder (int x, int y, double r, double height) { super(x, y, radius); setHeight(height); } public void setHeight (double h) { height = ( h < 0.0 ? 0.0 : h ); } public double getHeight () { return height; } public double getArea () { return 2 * super.getArea() + getCircumference() * getHeight(); } public double getVolume () { return super.getArea() * getHeight(); } public String getName () { return "Cylinder"; } public void draw () { // code to draw a cylinder goes here } }
Object-oriented programming Polymorphism
Polymorphism
Concrete classes allocated and instantiated as usual array of abstract class references each slot aims at a different subclass polymorphism: subclass method will be called, though superclass reference is used
Point: Area = 0.00 Volume = 0.00 Circle: Area = 38.48 Volume = 0.00 Cylinder: Area = 291.32 Volume = 367.78 public class AbstractInheritanceTest { public static void main (String args []) { Point point = new Point(7, 11); Circle circle = new Circle(22, 8, 3.5); Cylinder cylinder = new Cylinder(20, 30, 3.3, 10.75); Shape [] arrayOfShapes = new Shape[3]; arrayOfShapes[0] = point; arrayOfShapes[1] = circle; arrayOfShapes[2] = cylinder; for (int i = 0; i < arrayOfShapes.length; i++) { System.out.println("\n" + arrayOfShapes[i].getName() + ": " + "\nArea = " + arrayOfShapes[i].getArea() + "\nVolume = " + arrayOfShapes[i].getVolume()); } System.exit(0); } }
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
+ getFirstName() : String + getLastName() : String + getNationalInsuranceNumber() : String + setFirstName(String) : void + setLastName(String) : void + setNationalInsuranceNumber(String) : void + earnings() : Real + toString() : String
Employee + getWeeklySalary() : Real + setWeeklySalary(Real) : void
SalariedEmployee + getWage() : Real + getHours() : Real + setWage(Real) : void + setHours(Real) : void
HourlyEmployee + getGrossSales() : Real + getCommissionRate() : Real + setGrossSales(Real) : void + setCommissionRate(Real) : void
CommissionEmployee + getBaseSalary() : Real + setBaseSalary(Real) : void
BasePlusCommissionEmployee
Object-oriented programming Polymorphism
Polymorphism
abstract class so no instances allowed; subclasses will fill in missing details common behaviour: all employees have this behaviour, it belongs in the base class of the hierarchy abstract method: distinguishing feature of the hierarchy’s subclasses
public abstract class Employee { private String firstName; private String lastName; private String nINumber; public Employee (String first, String last, String nin) { firstName = first; lastName = last; nINumber = nin; } public void setFirstName (String first) { firstName = first; } public String getFirstName () { return firstName; } public void setLastName (String last) { lastName = last;} public String getLastName () { return lastName; } public void setNationalInsuranceNumber (String number) { nINumber = number; } public String getNationalInsuranceNumber () { return nINumber; } public String toString () { return getFirstName() + " " + getLastName() + "\nnational insurance number: " + getNationalInsuranceNumber(); } public abstract double earnings(); }
Object-oriented programming Polymorphism
Polymorphism
extend base class: must
since base class is abstract constructor: use super() and initialise extra variables class-specific: implement any class-specific behaviour concrete class: override and implement abstract method
public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee (String first, String last, String nin, double salary ) { super(first, last, nin); setWeeklySalary( salary ); } public void setWeeklySalary (double s) { weeklySalary = s < 0.0 ? 0.0 : s; } public double getWeeklySalary () { return weeklySalary; } public double earnings () { return getWeeklySalary(); } public String toString () { return "\nsalaried employee: " + super.toString(); } }
Object-oriented programming Polymorphism
Polymorphism
abstract method extend superclass and provide extra behaviour
public class HourlyEmployee extends Employee { private double wage; private double hours; public HourlyEmployee (String first, String last, String nINumber, double wage, double hours) { super(first, last, nINumber); setWage(wage); setHours(hours); } public void setWage (double w) { wage = w < 0.0 ? 0.0 : w; } public double getWage() { return wage; } public void setHours (double h) { hours = ( h >= 0.0 && h <= 168.0 ) ? h : 0.0; } public double getHours() { return hours; } public double earnings () { if (hours <= 40) return wage * hours; else return 40 * wage + (hours - 40) * wage * 1.5; } public String toString () { return "\nhourly employee: " + super.toString(); } }
Object-oriented programming Polymorphism
Polymorphism
abstract method extend superclass and provide extra behaviour
public class CommissionEmployee extends Employee { private double grossSales; private double commissionRate; public CommissionEmployee (String first, String last, String nin, double sales, double rate) { super(first, last, nin); setGrossSales(sales); setCommissionRate(rate); } public void setCommissionRate (double r) { commissionRate = ( r > 0.0 && r < 1.0 ) ? r : 0.0; } public double getCommissionRate () { return commissionRate; } public void setGrossSales (double s) { grossSales = s < 0.0 ? 0.0 : s; } public double getGrossSales () { return grossSales; } public double earnings () { return getCommissionRate() * getGrossSales(); } public String toString () { return "\ncommission employee: " + super.toString(); } }
Object-oriented programming Polymorphism
Polymorphism
extend CommissionEmployee and not Employee call superclass constructor and fill in the missing information provide class-specific behaviour
base class’s abstract method and use superclass’s implementation
public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary; public BasePlusCommissionEmployee (String first, String last, String nin, double sales, double rate, double base) { super(first, last, nin, sales, rate); setBaseSalary(base); } public void setBaseSalary (double s) { baseSalary = s < 0.0 ? 0.0 : s; } public double getBaseSalary () { return baseSalary; } public double earnings () { return getBaseSalary() + super.earnings(); } public String toString () { return "\nbase-salaried commission employee: " + super.toString(); } }
Object-oriented programming Polymorphism
Polymorphism
array of references: there can be references to abstract classes concrete classes: each array slot points to a different concrete class instance type checking: use instanceof to identify base-plus- commision employees downcasting: obtain a BasePlusCommissionEmployee reference to access extra functionality and give a raise polymorphism: call earnings()
method will be called class name check: ask Java the name of the referred class (again, polymorphism)
public class PayrollSystemTest { public static void main (String [] args) { Employee [] employees = new Employee[4]; employees[0] = new SalariedEmployee("John", "Smith", "111-11-1111", 800.00); employees[1] = new CommissionEmployee("Sue", "Jones", "222-22-2222", 10000, 0.06); employees[2] = new BasePlusCommissionEmployee("Bob", "Lewis", "333-33-3333", 5000, 0.04, 300); employees[3] = new HourlyEmployee("Karen", "Price", "444-44-4444", 16.75, 40); for (int i = 0; i < employees.length; i++ ) { System.out.println(employees[i].toString()); if (employees[i] instanceof BasePlusCommissionEmployee) { BasePlusCommissionEmployee currentEmployee = (BasePlusCommissionEmployee) employees[i]; double oldBaseSalary = currentEmployee.getBaseSalary(); System.out.println("old base salary: £" + oldBaseSalary; currentEmployee.setBaseSalary(1.10 * oldBaseSalary); System.out.println("new base salary with 10% increase is: £" + currentEmployee.getBaseSalary(); } System.out.println("earned £" + employees[i].earnings() + "\n"; } for (int j = 0; j < employees.length; j++) System.out.println("\nEmployee " + j + " is a " + employees[j].getClass().getName(); System.exit(0); } }
Object-oriented programming Polymorphism
Polymorphism
salaried employee: John Smith national insurance number: 111-11-111 earned £800.00 commission employee: Sue Jones national insurance number: 222-22-222 earned £600.00 base-salaried commission employee: Bob Lewis national insurance number: 333-33-333
new base salary with 10% increase is: £330.00 earned £530.00 hourly employee: Karen Price national insurance number: 444-44-444 earned £670.00 Employee 0 is a SalariedEmployee Employee 1 is a CommissionEmployee Employee 2 is a BasePlusCommissionEmployee Employee 3 is a HourlyEmployee public class PayrollSystemTest { public static void main (String [] args) { Employee [] employees = new Employee[4]; employees[0] = new SalariedEmployee("John", "Smith", "111-11-1111", 800.00); employees[1] = new CommissionEmployee("Sue", "Jones", "222-22-2222", 10000, 0.06); employees[2] = new BasePlusCommissionEmployee("Bob", "Lewis", "333-33-3333", 5000, 0.04, 300); employees[3] = new HourlyEmployee("Karen", "Price", "444-44-4444", 16.75, 40); for (int i = 0; i < employees.length; i++ ) { System.out.println(employees[i].toString()); if (employees[i] instanceof BasePlusCommissionEmployee) { BasePlusCommissionEmployee currentEmployee = (BasePlusCommissionEmployee) employees[i]; double oldBaseSalary = currentEmployee.getBaseSalary(); System.out.println("old base salary: £" + oldBaseSalary; currentEmployee.setBaseSalary(1.10 * oldBaseSalary); System.out.println("new base salary with 10% increase is: £" + currentEmployee.getBaseSalary(); } System.out.println("earned £" + employees[i].earnings() + "\n"; } for (int j = 0; j < employees.length; j++) System.out.println("\nEmployee " + j + " is a " + employees[j].getClass().getName(); System.exit(0); } }
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
public interface Shape { public double getArea(); public double getVolume(); public String getName(); } Object-oriented programming Polymorphism
Polymorphism
public class Point implements Shape { private int x; private int y; public Point () {} public Point (int x, int y) { this.x = x; this.y = y; } public void setX (int x) { this.x = x; } public int getX () { return x; } public void setY (int y) { this.y = y; } public int getY () { return y; } public double getArea () { return 0.0; } public double getVolume () { return 0.0; } public String getName () { return "Point"; } public String toString () { return "[" + getX() + ", " + getY() + "]"; } } Object-oriented programming Polymorphism
Polymorphism
Concrete classes allocated and instantiated as usual array of interface references: each slot aims at a class implementing the interface interfaces: appropriate method will be called, though interface reference is used
Point: Area = 0.00 Volume = 0.00 Circle: Area = 38.48 Volume = 0.00 Cylinder: Area = 291.32 Volume = 367.78 public class InterfaceTest { public static void main (String args []) { Point point = new Point(7, 11); Circle circle = new Circle(22, 8, 3.5); Cylinder cylinder = new Cylinder(20, 30, 3.3, 10.75); Shape arrayOfShapes[] = new Shape[3]; arrayOfShapes[0] = point; arrayOfShapes[1] = circle; arrayOfShapes[2] = cylinder; for (int i = 0; i < arrayOfShapes.length; i++) { System.out.println("\n" + arrayOfShapes[i].getName() + ": " + "\nArea = " + arrayOfShapes[i].getArea() + "\nVolume = " + arrayOfShapes[i].getVolume()); } } }
Object-oriented programming Polymorphism
Polymorphism
public interface Drawable { public void draw (Graphics g); }
multiple interfaces: use a comma- separated list to declare multiple interfaces a class implements concrete implementations: for each interface, provide the concrete implementation of the interface methods
public class Point implements Shape, Drawable { private int x; private int y; public Point () {} public Point (int x, int y) { this.x = x; this.y = y; } public void setX (int x) { this.x = x; } public int getX () { return x; } public void setY (int y) { this.y = y; } public int getY () { return y; } public double getArea () { return 0.0; } public double getVolume () { return 0.0; } public String getName () { return "Point"; } public void draw (Graphics g) { // code to draw a point } public String toString () { return "[" + getX() + ", " + getY() + "]"; } }
Object-oriented programming Polymorphism
Polymorphism
Point: Area = 0.00 Volume = 0.00 Circle: Area = 38.48 Volume = 0.00 Cylinder: Area = 291.32 Volume = 367.78
Concrete classes: allocated and instantiated as usual; each implements two interfaces two arrays: one with references to shapes, the other with references to drawable
same objects: but concerned about different behaviours appropriate behaviour: use different facets to invoke appropriate behaviour
public class MultipleInterfaceTest { public static void main (String args []) { Point point = new Point(7, 11); Circle circle = new Circle(22, 8, 3.5); Cylinder cylinder = new Cylinder(20, 30, 3.3, 10.75); int numShapes = 3; Shape arrayOfShapes[] = new Shape[num]; arrayOfShapes[0] = point; arrayOfShapes[1] = circle; arrayOfShapes[2] = cylinder; Drawable arrayOfDrawables[] = new Drawable[num]; arrayOfDrawables[0] = point; arrayOfDrawables[1] = circle; arrayOfDrawables[2] = cylinder; // code to initialise the graphics system for (int i = 0; i < num; i++) { System.out.println("\n" + arrayOfShapes[i].getName() + ": " + "\nArea = " + arrayOfShapes[i].getArea() + "\nVolume = " + arrayOfShapes[i].getVolume()); arrayOfDrawables[i].draw(graphics); } } }
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism
Polymorphism
Object-oriented programming Polymorphism