Download presentation
Presentation is loading. Please wait.
Published byLouise McDowell Modified over 6 years ago
1
Lecture Notes – Interface and Polymorphism (Ch 9-10)
Yonglei Tao
2
Polymorphism A reference of a super class can refer to an object of any descendent class Allowing objects of different classes to respond to the same method call in different ways Benefits No need to use conditional logic Simplify the client code Extensible
3
Abstract Classes Represent an abstract concept Cannot be instantiated
public abstract class Employee { protected String name; protected double basePay; … public abstract double calcBiweeklyPay (); } Represent an abstract concept Cannot be instantiated A subclass must define all of its parent’s abstract methods or itself is an abstract class
4
An Example // in class Employee
public abstract double calcBiWeeklyPay (); // in class Worker public double calcBiWeeklyPay () { return hours * basePay; } // in class Manager public double calcBiWeeklyPay () { return basePay / 26; } // in client code Employee list[] = new Employee[30]; List [0] = new Worker (“Tom”, 12.5); List [1] = new Manager (“John”, 36000); List [2] = new Worker (“Ed”, 11.25); … for (int i = 0; i < list.length; i++) { System.out.print ( list[i] ); System.out.println ( list[i].calcBiWeeklyPay () ); }
5
Dynamic Binding Employee p; Worker w = new Worker(“Tom”, 7.95, 40);
Manager m = new Manager(“John”, 36000); … // either p = w or p = m w.calcBinweeklyPay(); // static/early binding m.calcBinweeklyPay(); p.calcBiweeklyPay(); // dynamic/late binding The binding of a method call to its definition is performed at runtime for a polymorphic reference
6
Class Shape public abstract class Shape { private String name;
public abstract double area (); public Shape( String shapeName ) { name = shapeName; } final public boolean lessThan ( Shape other ) { return area() < other.area(); final public String toString () { return name + " of area " + area();
7
Circle Rectangle public class Rectangle extends Shape { private double length, width; public Rectangle ( double len, double wid ) { super ( "rectangle" ); length = len; width = wid; } public double area () { return length * width;
8
Class Circle public class Circle extends Shape { private double radius; public Circle( double radius ) { super ( "circle" ); this.radius = radius; } public double area () { return Math.PI * radius * radius;
9
Class Square public class Square extends Rectangle {
public Square ( double side ) { super ( side, side ); }
10
public class ShapeTest { final static int MaxSize = 50; public static void main ( String[] args ) { Shape[] shapeList = new Shape [ MaxSize ]; int size = 0, choice; for ( int i = 0; i < 15; i++ ) { // object construction choice = (int) ( Math.random() * 3 ); switch ( choice ) { case 0: shapeList[size++] = new Circle( size*1.25 ); break; case 1: shapeList[size++] = new Rectangle( size+2.5, size*7.0 ); case 2: shapeList[size++] = new Square ( size*5.0 ); }
11
What needs to be done if a new subclass is added?
// processing of objects for ( int i = 0; i < size; i++ ) { System.out.println( shapeList[i] ); } double total = 0; total += shapeList[i].area(); System.out.println( "The total are is " + total ); What needs to be done if a new subclass is added?
12
Interfaces interface is a reserved word None of the methods in
an interface are given a definition (body) public interface Doable { public void doThis(); public int doThat(); } A semicolon immediately follows each method header
13
Interfaces public class CanDo implements Doable {
public void doThis () // whatever } public void doThat () // instance variables and methods implements is a reserved word Each method listed in Doable is given a definition
14
Interfaces
15
Interface and Its Implementation
public interface Measurable { double getMeasure(); } public class Coin implements Measurable { private double value; private String name; public double getMeasure() { return value; public String getName() { … } ... public class BankAccount implements Measurable { private double balance; public double getMeasure() { return balance; } … }
16
DataSet for Measurable Objects
public class DataSet { private double sum; private Measurable max; private int count; public void add(Measurable x) { sum = sum + x.getMeasure(); if (count==0 || max.getMeasure()< x.getMeasure()) max = x; count++; } public double getAverage() { return sum/count; } public Measurable getMaximum() { return max; } } A reference of an interface can refer to an object of any implementation class
17
public class DataSetTester {
public static void main(String[] args) { DataSet bankData = new DataSet(); bankData.add(new BankAccount(0)); bankData.add(new BankAccount(10000)); bankData.add(new BankAccount(2000)); System.out.println("Average balance: " + bankData.getAverage()); System.out.println("Expected: 4000"); Measurable max = bankData.getMaximum(); System.out.println("Highest balance: " + max.getMeasure()); System.out.println("Expected: 10000"); DataSet coinData = new DataSet(); coinData.add(new Coin(0.25, "quarter")); coinData.add(new Coin(0.1, "dime")); coinData.add(new Coin(0.05, "nickel")); System.out.println("Average coin value: “ + coinData.getAverage()); System.out.println("Expected: 0.133"); max = coinData.getMaximum(); System.out.println("Highest coin value: " + max.getMeasure()); System.out.println("Expected: 0.25"); }
18
Interfaces vs. Classes An interface is similar to a class, but there are several important differences: All methods in an interface are abstract; they don’t have an implementation All methods in an interface are automatically public Instance variables in an interface are always static or final A class may implement multiple interfaces
19
Type Conversion Implicit conversion Explicit conversion
intVar = charExpr; floatVar = intExpr; doubleVar = floatExpr; Worker w = new Worker (); Employee p = w; Explicit conversion char ch = (char) anInt; // anInt = 65 long num = (long) aDouble; // aDouble = 7.99
20
Explicit Conversion Employee p; Worker w = new Worker(“Tom”, 7.95, 40); Manager m = new Manager(“John”, 36000); … // either p = w or p = m w = p; ? public void aMethod ( Employee p ) { if ( p instanceof Worker ) Worker w = (Worker) p; … }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.