Polymorphism Object-oriented programming Inf1 :: 2008 - - PowerPoint PPT Presentation

polymorphism
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

Polymorphism

Polymorphism

Object-oriented programming Inf1 :: 2008

Object-oriented programming Polymorphism

slide-2
SLIDE 2

Polymorphism

Overview

Polymorphism is a concept that allows the programmer to program abstractly

Objects of a subclass can be treated as objects of its superclass(es)

The base class of a hierarchy is usually an abstract class Allows for hierarchies to be highly extensible

New classes can be introduced and can still be processed without changing other parts of the program

Object-oriented programming Polymorphism

slide-3
SLIDE 3

Polymorphism

Abstract classes

Abstract classes define the common behaviour (functionality)

  • f the hierarchy — also known as an interface

Subclasses inherit this behaviour and extend it according to their own properties by overriding the methods of the superclass

Key concept: subclass objects can be treated as superclass

  • bjects through references

But, superclass objects are not subclass objects

Abstract classes cannot be instantiated

Object-oriented programming Polymorphism

slide-4
SLIDE 4

Polymorphism

More on references

A superclass reference can be assigned to a superclass variable

Point p = new Point( 50, 50);

A subclass reference can be assigned to a subclass variable

Circle c = new Circle( 60, 60, 6.0);

A subclass reference can be assigned to a superclass variable

p = c; A Circle is a (extends a) Point

Object-oriented programming Polymorphism

slide-5
SLIDE 5

Polymorphism

Example

point coordinates x = 50, y = 50 circle coordinates x = 60, y = 60 anotherPoint coordinates x = 60, y = 60

superclass reference to superclass instance subclass reference to subclass instance superclass reference to subclass instance polymorphism: subclass methods will be called

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

slide-6
SLIDE 6

Polymorphism

What about the inverse?

It is perfectly acceptable to assign a subclass reference to a superclass variable; can we do the inverse? i.e., assign a superclass reference to a subclass variable This will generate a compiler error The reason is simple: a Point is not a Circle Circle has data/behaviour that Point does not have

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

slide-7
SLIDE 7

Polymorphism

Downcasting

Superclass variable, assigned a subclass reference (permissible) Can we invoke a subclass-specific method?

Circle c = new Circle(60, 60, 6.0); Point p = c; Sytstem.out.println(p.getRadius());

This is not permitted; subclass methods are not superclass methods! The compiler can, however, be explicitly instructed to do it — this is called downcasting

System.out.println((Circle) p.getRadius());

Called downcasting, because an object higher in the hierarchy is converted to an object lower (down) in the hierarchy

Object-oriented programming Polymorphism

slide-8
SLIDE 8

Polymorphism

Invoking subclass behaviour from a superclass

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

slide-9
SLIDE 9

Polymorphism

Downcasting example

downncasting: explicitly instruct the compiler that point is a reference to a Circle instance; prone to runtime 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 = ((Circle) point).getRadius(); ((Circle) point).setRadius(33.33); double diameter = ((Circle) point).getDiameter(); double circumference = ((Circle) point).getCircumference(); double area = ((Circle) point).getArea(); } }

Downcasting is tricky Use downcasting only if you are absolutely certain it will succeed

Object-oriented programming Polymorphism

slide-10
SLIDE 10

Polymorphism

More polymorphism examples

Suppose, in a hierarchy of shapes, Rectangle extends Quadrilateral

Rectangle is more specific than Quadrilateral Any operation permitted on Quadrilateral can be carried

  • ut on a Rectangle

Suppose you are designing a video game and you have many subclasses of SpaceShip

SpaceShip and all its subclasses have a method called draw() When refreshing the screen, you need not know the exact type

  • f a spaceship

Treat them all as SpaceShip instances and call SpaceShip.draw() Each subclass-specific draw() method will be called due to polymorphism You can keep adding different types of spaceship without modifying the code that refreshes the screen

Object-oriented programming Polymorphism

slide-11
SLIDE 11

Polymorphism

Abstract classes and methods

Abstract classes

Are superclasses (also called abstract superclasses) Cannot be instantiated, but references to them are possible Are usually incomplete — subclasses fill in the details according to their own behaviour

They provide abstract methods, which do not have implementation and must be overriden

Are not required in a hierarchy, but reduce code dependency when present

Concrete classes

Are derived from abstract classes Can be instantiated Implement every single method they declare and provide specific behaviour

Object-oriented programming Polymorphism

slide-12
SLIDE 12

Polymorphism

Shapes extended

+ getX() : Integer + getY() : Integer + setX(Integer) : void + setY(Integer) : void

  • Integer x = 0
  • Integer y = 0

Point + getRadius() : Real + setRadius(Real) : void + getDiameter() : Real + getCircumference() : Real

  • Real radius = 0.0

Circle + getHeight() : Real + setHeight(Real) : void

  • Real height = 0.0

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

slide-13
SLIDE 13

Polymorphism

The Shape class

abstract keyword: declares the Shape class as an abstract class; disallows new instances to be created default implementation: though Shape is abstract, it can still have default behaviour abstract methods: declared without an implementation; subclasses must override them

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

slide-14
SLIDE 14

Polymorphism

The Point class

concrete class derived from an abstract class abstract methods must be overriden by concrete classes non-abstract methods do not need to be overriden (getArea(), getVolume()) if their default behaviour is OK

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

slide-15
SLIDE 15

Polymorphism

The Circle class

subclass-specific code and behaviour no need to override getVolume(); Shape‘s implementation is still OK abstract methods are

  • verriden for

Circle

  • verriding: Circle.getArea()

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

slide-16
SLIDE 16

Polymorphism

The Cylinder class

subclass-specific behaviour

  • verride

getArea() and getVolume(); existing definitions are wrong abstract methods

  • verridden for

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

slide-17
SLIDE 17

Polymorphism

Putting it all together

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

slide-18
SLIDE 18

Polymorphism

final methods and classes

A final method or class is Java’s way of prohibiting inheritance and/or overriding Final methods

access mode final methodName (arguments) Cannot be overridden by subclasses All private methods are implicitly final

Final classes

access-mode final ClassName [extends SuperClass] Cannot be extended All their methods are implicitly final

Object-oriented programming Polymorphism

slide-19
SLIDE 19

Polymorphism

Case study: a payroll system

Create a payroll system using abstract classes, inheritance and polymorphism Four types of employees, paid weekly

Salaried employees: fixed salary irrespective of hours Hourly employees: overtime (> 40 hours) pays time and a half Commission employees: paid by a percentage of sales Base-plus-commission employees: base salary and a percentage

  • f sales

The information known about each employee is his/her first name, last name, and national insurance number

The rest depends on the type of employee

Object-oriented programming Polymorphism

slide-20
SLIDE 20

Polymorphism

Payroll system: UML diagram

+ getFirstName() : String + getLastName() : String + getNationalInsuranceNumber() : String + setFirstName(String) : void + setLastName(String) : void + setNationalInsuranceNumber(String) : void + earnings() : Real + toString() : String

  • String firstName
  • String lastName
  • String nINumber

Employee + getWeeklySalary() : Real + setWeeklySalary(Real) : void

  • Real weeklySalary

SalariedEmployee + getWage() : Real + getHours() : Real + setWage(Real) : void + setHours(Real) : void

  • Real wage
  • Real hours

HourlyEmployee + getGrossSales() : Real + getCommissionRate() : Real + setGrossSales(Real) : void + setCommissionRate(Real) : void

  • Real grossSales
  • Real commissionRate

CommissionEmployee + getBaseSalary() : Real + setBaseSalary(Real) : void

  • Real baseSalary

BasePlusCommissionEmployee

Object-oriented programming Polymorphism

slide-21
SLIDE 21

Polymorphism

Payroll system: Employee class

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

slide-22
SLIDE 22

Polymorphism

Payroll system: SalariedEmployee class

extend base class: must

  • verride abstract methods

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

  • f the superclass

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

slide-23
SLIDE 23

Polymorphism

Payroll system: HourlyEmployee class

  • verride base class’s

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

slide-24
SLIDE 24

Polymorphism

Payroll system: CommissionEmployee class

  • verride base class’s

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

slide-25
SLIDE 25

Polymorphism

Payroll system: BasePlusCommissionEmployee class

extend CommissionEmployee and not Employee call superclass constructor and fill in the missing information provide class-specific behaviour

  • verride and implement

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

slide-26
SLIDE 26

Polymorphism

Payroll system: putting it all together

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

  • n Employee reference; subclass

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

slide-27
SLIDE 27

Polymorphism

Payroll system: results

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

  • ld base salary: £300.00

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

slide-28
SLIDE 28

Polymorphism

Interfaces

An interface is a way of specifying behaviour alone No data members, just a collection of method declarations Interface declaration begins with the interface keyword A class may implement an interface

Declared through implements interface name

An interface declaration contains the method signatures — no body Classes implementing the interface must provide concrete implementations for the interface methods Interfaces are not classes! They are not instantiated

But we can have references to classes implementing an interface

Interfaces are inherited, i.e., subclasses of a class implementing an interface implicitly implement it themselves

Object-oriented programming Polymorphism

slide-29
SLIDE 29

Polymorphism

A Shape as an interface

interface declaration: use interface instead of class; can still have access modifiers no constructor: an interface only defines behaviour no body: all methods implementing the interface must provide the concrete implementations

public interface Shape { public double getArea(); public double getVolume(); public String getName(); } Object-oriented programming Polymorphism

slide-30
SLIDE 30

Polymorphism

Point implementing the Shape interface

interface implementation: Point has the behaviour

  • f a Shape

concrete implementation: Point must specify the implementations for the methods of the Shape interface

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

slide-31
SLIDE 31

Polymorphism

Putting it all together

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

slide-32
SLIDE 32

Polymorphism

Implementing multiple interfaces

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

slide-33
SLIDE 33

Polymorphism

Multiple interfaces example

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

  • bjects

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

slide-34
SLIDE 34

Polymorphism

Abstract classes or interfaces?

Abstract classes and interfaces have similar functionality

They both define behavioural aspects

However, there are differences

Abstract classes have data, there are no data in interfaces Abstract classes may also have state-related logic associated; interfaces do not Interfaces are only a declaration of behaviour — they are not expected to modify the state of an object

If a hierarchy is expected to be built, and there are data associated with an object, then use abstract classes Behaviour that transcends hierarchies (i.e., many classes of different hierarchies are expected to have similar behaviour) then use interfaces

Object-oriented programming Polymorphism

slide-35
SLIDE 35

Polymorphism

Things to do

To do Read Deitel & Deitel, Chapter 10, Sections 10.1 — 10.7 Understand how polymorphism works Go over your first assignment and figure out how things work Understand the difference between abstract class hierarchies and interfaces and when we should use which

Object-oriented programming Polymorphism