comp dynamic dispatch and abstract methodsdewan/comp114/f12/lectures/... · comp 401 dynamic...

60
COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

Upload: others

Post on 10-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

COMP 401

DYNAMIC DISPATCH AND

ABSTRACT METHODS

Instructor: Prasun Dewan

Page 2: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

2

A POINTHISTORY IMPLEMENTATION public class APointHistory implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {return size == MAX_SIZE;}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = new ACartesianPoint(x, y);

contents[size] = p;

size++;

}

}

}

Page 3: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

3

A POLARPOINTHISTORY IMPLEMENTATION public class APolarPointHistory implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {return size == MAX_SIZE;}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = new APolarPoint(x, y);

contents[size] = p;

size++;

}

}

}

Reducing code duplication?

Page 4: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

4

A POLARPOINTHISTORY IMPLEMENTATION

public class APolarPointHistoryWithAddMethod

extends APointHistory {

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = new APolarPoint(x, y);

contents[size] = p;

size++;

}

}

}

Only line changed, still code duplication

Page 5: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

5

A POINTHISTORY IMPLEMENTATION public class ACartesianPointHistoryWithDynamicallyDispatchedMethod

implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

protected Point createPoint(int x, int y) {

return new ACartesianPoint(x, y);

}

}

Page 6: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

6

OVERRIDING METHOD

public class APolarPointHistoryWithDynamicallyDispatchedMethod

extends ACartesianPointHistoryWithDynamicallyDispatchedMethod {

protected Point createPoint(int x, int y) {

return new ACartesianPoint(x, y);

}

}

public static void main (String[] args) {

PointHistory pointHistory =

new APolarPointHistoryWithDynamicallyDispatchedMethod();

pointHistory.addElement(50, 100);

}

Page 7: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

7

A POINTHISTORY IMPLEMENTATION public class ACartesianPointHistoryWithDynamicallyDispatchedMethod

implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

protected Point createPoint(int x, int y) {

return new ACartesianPoint(x, y);

}

}

public class APolarPointHistoryWithDynamicallyDispatchedMethod

extends ACartesianPointHistoryWithDynamicallyDispatchedMethod {

protected Point createPoint(int x, int y) {

return new ACartesianPoint(x, y);

}

}

PointHistory pointHistory =

new APolarPointHistoryWithDynamicallyDispatchedMethod();

pointHistory.addElement(50, 100);

Static dispatching: call most specific method

known when caller method was compiled

Dynamic dispatching: call most specific

method for the calling object

Page 8: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

8

VIRTUAL VS. REGULAR METHOD AND DIFFERENT

LANGUAGES

Virtual method: Call to it is dynamically dispatched

Regular method: Call to it is statically dispatched

Java: All instance methods are virtual methods and all class (static)methods are regular methods

C++: Instance methods can be declared to be regular or virtual and all class (static)methods are regular methods

Smalltalk: All methods are virtual

Page 9: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

9

INHERITANCE RELATIONSHIPS?

APolarPointHistoryWithDynamicallyDispatchedMethod

ACartesianPointHistoryWithDynamicallyDispatchedMethod

IS-A

APolarPointHistoryWithDynamicallyDispatchedMethod

ACartesianPointHistoryWithDynamicallyDispatchedMethod

IS-A

Page 10: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

10

CORRECT INHERITANCE

AnAbstractPointHistory

ACartesianPointHistory

IS-A

APolarPointHistory

IS-A

Page 11: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

11

CORRECT INHERITANCE

AnAbstractPointHistory

ACartesianPointHistory

IS-A

APolarPointHistory

IS-A

Page 12: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

12

A CATERSIAN HISTORY IMPLEMENTATION public class ACartesianPointHistoryWithDynamicallyDispatchedMethod

implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

protected Point createPoint(int x, int y) {

return new ACartesianPoint(x, y);

}

}

Changed how?

Page 13: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

13

REMOVING CREATEPOINT

public abstract class AnAbstractPointHistory implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

}

Page 14: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

14

NULL OVERRIDDEN METHOD

public abstract class AnAbstractPointHistory implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

protected Point createPoint(int x, int y) {}

}

Page 15: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

15

OVERRIDING DYNAMICALLY DISPATCHED METHOD

public class ACartesianPointHistory

extends AnAbstractPointHistory{

protected Point createPoint(int x, int y) {

return new ACartesianPoint(x, y);

}

}

Page 16: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

16

ERRONEOUS IMPLEMENTATION WITH NO ERRORS

public class ACartesianPointHistory extends AnAbstractPointHistory{

}

Page 17: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

17

ABSTRACT METHOD

public abstract class AnAbstractPointHistory implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

protected abstract Point createPoint(int x, int y);

}

Only header of method provided as in interface

Page 18: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

18

ERRONEOUS IMPLEMENTATION

Java complains abstract method not implemented in concrete class

public class ACartesianPointHistory extends AnAbstractPointHistory{

}

Page 19: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

19

NULL VS. ABSTRACT METHODS

Null methods could replace abstract methods.

Abstract method force overriding implementations in subclasses.

Provide better documentation, indicating to programmer that subclass will implement them.

Page 20: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

20

ABSTRACT METHOD

Declared only in abstract classes

Keyword: abstract

No body

Each (direct or indirect) subclass must implement

abstract methods defined by an abstract class.

Much like each class must implement the methods

defined by its interface(s).

Page 21: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

21

ABSTRACT CLASS VS. METHODS

Abstract method => containing class abstract

Cannot have an unimplemented method in an instance

Abstract class may not contain abstract method

Page 22: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

22

A COURSE WITH ABSTRACT METHOD

public abstract class ACourse {

String title, dept;

public ACourse (String theTitle, String theDept) {

super();

title = theTitle;

dept = theDept;

}

public String getTitle() {

return title;

}

public String getDepartment() {

return dept;

}

abstract public int getNumber();

public String toString() {

return "Title:" + title + " Dept:" + dept +

" Number: " + getNumber();

} Abstract Method

Page 23: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

23

EQUIVALENT WITH INTERFACE

public abstract class ACourse implements Course {

String title, dept;

public ACourse (String theTitle, String theDept) {

super();

title = theTitle;

dept = theDept;

}

public String getTitle() {

return title;

}

public String getDepartment() {

return dept;

}

public String toString() {

return "Title:" + title + " Dept:" + dept +

" Number: " + getNumber();

} An abstract class can

implement any

interface

This means all sub

classes implement the

interface

Interface implementation

check is made for concrete

classes

Page 24: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

24

ANOTHER COURSE

package courses;

public abstract class ACourse implements Course {

String title, dept;

public ACourse (String theTitle, String theDept) {

super();

title = theTitle;

dept = theDept;

}

public String getTitle() {

return title;

}

public String getDepartment() {

return dept;

}

public String toString() {

return "Title:" + title + " Dept:" + dept + " Number: " +

getNumber();

}

}

An abstract class can

implement any

interface

This means all sub

classes implement the

interface

Interface implementation

check is made for concrete

classes

Page 25: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

25

ALTERNATIVE AREGULARCOURSE

public class ARegularCourse extends ACourse {

int courseNum;

public ARegularCourse (String theTitle, String theDept, int

theCourseNum) {

super (theTitle, theDept);

courseNum = theCourseNum;

}

public int getNumber() {

return courseNum;

}

}

Saying ARegularCourse implements Course is redundant

Page 26: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

26

ALTERNATIVE AFRESHMANSEMINAR

public class AFreshmanSeminar extends ACourse {

public AFreshmanSeminar (String theTitle, String theDept) {

super (theTitle, theDept);

}

public int getNumber() {

return SEMINAR_NUMBER;

}

}

No need for implementation clause

Page 27: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

27

public abstract class AnAbstractPointHistory implements PointHistory {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

protected abstract Point createPoint(int x, int y);

}

WHEN ABSTRACT METHOD REQUIRED

Not public

Page 28: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

28

ADDING CREATEPOINT TO INTERFACE public interface PointHistoryWithExtraPublicMethod {

public Point createPoint(int x, int y);

}

public abstract class AnAbstractPointHistoryWithExtraPublicMethod

implements PointHistoryWithExtraPublicMethod {

public final int MAX_SIZE = 50;

protected Point[] contents = new Point[MAX_SIZE];

protected int size = 0;

public int size() {

return size;

}

public Point elementAt (int index) {

return contents[index];

}

protected boolean isFull() {

return size == MAX_SIZE;

}

public void addElement(int x, int y) {

if (isFull())

System.out.println("Adding item to a full history");

else {

Point p = createPoint(x, y);

contents[size] = p;

size++;

}

}

}

Least privilege violated

Factory method

Page 29: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

29

FACTORY ABSTRACT METHOD

abstract <T> <M>(…) ;

<T> <M>(…) {

return new <C1> (…)

}

extends

<T> <M> (…){

return new <C2> (…)

}

Abstract method that returns an instance of

some type T – like a factory, it creates and

initializes an object.

Page 30: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

30

ABSTRACT METHODS VS. INTERFACES

Unimplemented methods become abstract methods to be implemented by concrete subclasses. Do not need explicit implements clause in subclass if no additional public methods implemented, public class ARegularCourse extends ACourse {

….

}

A class with only abstract methods simulates interfaces.

No multiple inheritance in Java

Separation of abstract and concrete methods with interfaces.

A class implements but does not inherit a specification!

Page 31: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

31

ABSTRACT METHODS VS. INTERFACES

Non-public abstract methods relevant even in Java

All interface methods must be public.

May want non public abstract methods.E.g.

abstract boolean isFull() ;

Page 32: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

32

ABSTRACT METHODS VS. VIRTUAL METHODS

Abstract methods must be virtual methods.

Virtual methods need not be abstract methods

Page 33: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

33

FACTORY METHODS VS. ABSTRACT METHODS

Some abstract methods may be factory methods

Factory methods may not be abstract methods but

often this means bad programming practice

APolarPointHistoryWithDynamicallyDispatchedMethod

ACartesianPointHistoryWithDynamicallyDispatchedMethod

IS-A

Page 34: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

34

OVERLOADING, POLYMORPHISM, AND

DYNAMIC DISPATCH

static void print (Course course) {

System.out.println(

course.getTitle() + " " +

course.getDepartment() +

course.getNumber()

);

}

static void print (CourseList courseList) {

print(course);

} Overloaded method

Dynamically dispatched

method

getNumber() in

ARegularCouse

getNumber() in

AFreshmanSeminar

ARegularCourse

AFreshmanSeminar

Polymorphic method

Page 35: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

35

OVERLOADING, POLYMORPHISM, AND

DYNAMIC DISPATCH

Same method name works on different types.

Overloading Multiple (static or instance) methods with same name

but different parameter types.

Resolved at compile time based on parameter types

Polymorphism Same method implementation works on multiple

object types.

Dynamic dispatch (or virtual methods) Multiple instance methods with same name in

different classes

Resolved at execution time based on type of target object

Page 36: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

36

POLYMORPHISM VS. OVERLOADING

AND DYNAMIC DISPATCH Polymorphism vs. Overloading

Polymorphism: single print (Course course)

Overloading: print (ARegularCourse course) and print (AFreshmanSeminar course) with same implementation.

Polymorphism vs. Dynamic Dispatch Polymorphism: single getTitle() in ACourse

Dynamic dispatch: getTitle() in AFreshmanSeminar() and getTitle() in ARegularCourse() with same implementation.

Create polymorphic code when you can In overloading and dynamic dispatch, multiple

implementations associated with each method name.

In polymorphic case, single implementation. Use interfaces rather than classes as types of parameters

Use supertypes rather than subtypes as types of parameters

Page 37: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

37

POLYMORPHISM VS. OVERLOADING

AND DYNAMIC DISPATCH Cannot always create polymorphic method.

getNumber() for ARegularCourse and AFreshmanSeminar do different things.

print(Course course) and print (CourseList courseList) do different things.

When polymorphism not possible try overloading and dynamic dispatch.

Page 38: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

38

MANUAL INSTEAD OF DYNAMIC DISPATCH

static void print (Course course) {

if (course instanceof ARegularCourse)

number = ((ARegularCourse)course).

getCourseNumberRegularCourse ();

else if (course instanceof AFreshmanSeminar)

number = ((AFreshmanSeminar)course).

getCourseNumberFreshmanSeminar ();

System.out.println(

course.getTitle() + " " +

course.getDepartment() +

number );

}

More Work Must update code as

subtypes added

Page 39: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

39

CAN WE GET RID OF MANUAL

DISPATCH/INSTANCEOF?

static void print (Course course) {

if (course instanceof RegularCourse)

System.out.print(“Regular Course: ”);

else if (course instanceof AFreshmanSeminar)

System.out.println(“Freshman Seminar”);

System.out.println(

course.getTitle() + " " +

course.getDepartment() +

course.getNumber() );

}

Page 40: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

40

CANNOT ALWAYS GET RID OF MANUAL

DISPATCH/INSTANCOF

static void print (Course course) {

printHeader (course);

System.out.println(

course.getTitle() + " " +

course.getDepartment() +

course.getNumbert() );

}

static void printHeader (ARegularCourse course) {

System.out.print(“Regular Course: ”);

}

static void printHeader (AFreshmanSeminar course) {

System.out.print(“Freshman Seminar: ”);

}

At compile time, do not know if

regular course or freshman

seminar

Actual parameter

cannot be

supertype of

formal parameter

Page 41: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

41

PRINTHEADER() IN AREGULARCOURSE

package courses;

public class ARegularCourse extends ACourse implements Course {

public void printHeader () {

System.out.print (“Regular Course: ”)

}

}

Page 42: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

42

PRINTHEADER() IN

AFRESHMANSEMINAR

package courses;

public class AFreshmanSeminar extends ACourse implements

FreshmanSeminar {

public void printHeader () {

System.out.print (“Freshman Seminar: ”)

}

}

Page 43: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

43

static void print (Course course) {

printHeader (course);

System.out.println(

course.getTitle() + " " +

course.getDepartment() +

course.getNumbert() );

}

static void printHeader (ARegularCourse course) {

System.out.print(“Regular Course: ”);

}

static void printHeader (AFreshmanSeminar course) {

System.out.print(“Freshman Seminar: ”);

}

SHOULD NOT ALWAYS GET RID OF MANUAL

DISPATCH/INSTANCOF

Should not put printHeader() in ARegularCourse or AFreshmanSeminar as it is UI code.

Hence need to use instanceof

Used in parsers

Page 44: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

44

EXTRA SLIDES

Page 45: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

45

A STRINGHISTORY IMPLEMENTATION

public class AStringHistory implements StringHistory {

public static final int MAX_SIZE = 50;

String[] contents = new String[MAX_SIZE];

int size = 0;

public int size() { return size;}

public String elementAt (int index) { return contents[index]; }

boolean isFull() { return size == MAX_SIZE; }

public void addElement(String element) {

if (isFull())

System.out.println("Adding item to a full history");

else {

contents[size] = element;

size++;

}

}

}

Page 46: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

46

A BIG STRINGHISTORY IMPLEMENTATION

public class ABigStringHistory implements StringHistory {

public static final int MAX_SIZE = 500;

String[] contents = new String[MAX_SIZE];

int size = 0;

public int size() { return size;}

public String elementAt (int index) { return contents[index]; }

boolean isFull() { return size == MAX_SIZE; }

public void addElement(String element) {

if (isFull())

System.out.println("Adding item to a full history");

else {

contents[size] = element;

size++;

}

}

}

Page 47: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

47

NULL OVERRIDDEN METHOD

public abstract class AnAbstractStringHistory {

boolean isFull(){};

void uncheckedAddElement(Object element){};

public void addElement(Object element) {

if (!isFull())

uncheckedAddElement(element);

else

handleError();

}

void handleError () {

System.out.println("Adding item to a full history");

};

}

Page 48: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

48

A STRINGHISTORY IMPLEMENTATION

public class AStringHistory extends AnAbstractStringHistory

implements StringHistory {

public final int MAX_SIZE = 50;

String[] contents = new String[MAX_SIZE];

int size = 0;

public int size() { return size;}

public String elementAt (int index) { return contents[index]; }

boolean isFull() { return size == MAX_SIZE; }

void uncheckedAddElement(String element) {

contents[size] = element;

size++;

}

}

Page 49: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

49

DYNAMIC DISPATCH public abstract class ACollection {

boolean isFull(){};

void uncheckedAddElement(Object element){};

public void addElement(Object element) {

if (!isFull())

uncheckedAddElement(element);

else

handleError();

}

void handleError () {

System.out.println("Adding item to a full history");

};

}

public class AStringHistory extends ACollection implements StringHistory {

boolean isFull() { return size == MAX_SIZE; }

void uncheckedAddElement(String element) {

contents[size] = element;

size++;

}

} Which isFull() called when addElement is invoked on an

instance of AStringHistory()?

Regular method: called method “statically dispatched” at compile time, so

overridden isFull()

Virtual method: most specific implementation of called method

“dynamically dispatched” at execution time, so overriding isFull()

Page 50: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

50

REGULAR VS. VIRTUAL METHOD

Smalltalk: had only virtual methods

With each object a table kept which associates method

header with most specific implementation.

Table accessed at execution time.

C++: Had both virtual and regular methods

More efficient with regular methods

Java: Has only virtual methods

Abstract and interface method by definition are virtual

methods

Page 51: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

51

CORRECT A BIG STRINGHISTORY

IMPLEMENTATION

public class ABigStringHistory extends AnAbstractStringHistory

implements StringHistory {

public final int MAX_SIZE = 500;

String[] contents = new String[MAX_SIZE];

int size = 0;

public int size() { return size;}

public String elementAt (int index) { return contents[index]; }

boolean isFull() { return size == MAX_SIZE; }

void uncheckedAddElement(String element) {

contents[size] = element;

size++;

}

}

Page 52: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

52

AN ERRONEOUS BIG STRINGHISTORY

IMPLEMENTATION

public class ABigStringHistory extends AnAbstractStringHistory

implements StringHistory {

public final int MAX_SIZE = 500;

String[] contents = new String[MAX_SIZE];

int size = 0;

public int size() { return size;}

public String elementAt (int index) { return contents[index]; }

boolean isFull() { return size == MAX_SIZE; }

//void uncheckedAddElement(String element) {

// contents[size] = element;

// size++;

//}

}

Page 53: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

53

NULL OVERRIDDEN METHOD

public abstract class AnAbstractStringHistory {

boolean isFull(){};

void uncheckedAddElement(Object element){};

public void addElement(Object element) {

if (!isFull())

uncheckedAddElement(element);

else

handleError();

}

void handleError () {

System.out.println("Adding item to a full history");

};

}

Page 54: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

54

ABSTRACT METHODS

public abstract class AnAbstractStringHistory {

abstract boolean isFull();

abstract void uncheckedAddElement(Object element)

public void addElement(Object element) {

if (!isFull())

uncheckedAddElement(element);

else

handleError();

}

void handleError () {

System.out.println("Adding item to a full history");

};

}

Only header of method provided as in

interface

Page 55: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

55

AN ERRONEOUS BIG STRINGHISTORY

IMPLEMENTATION

public class ABigStringHistory implements StringHistory {

public final int MAX_SIZE = 500;

String[] contents = new String[MAX_SIZE];

int size = 0;

public int size() { return size;}

public String elementAt (int index) { return contents[index]; }

boolean isFull() { return size == MAX_SIZE; }

//void uncheckedAddElement(String element) {

// contents[size] = element;

// size++;

//}

}

Java complains abstract method not

implemented in concrete class

Page 56: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

56

NULL VS. ABSTRACT METHODS

public abstract class AnAbstractStringHistory {

boolean isFull() {}

void uncheckedAddElement(Object element) {}

public void addElement(Object element) {

if (!isFull())

uncheckedAddElement(element);

else

handleError();

}

void handleError () {

System.out.println("Adding item to a full history");

};

}

Null methods could replace

abstract methods in this example.

Abstract method force overriding

implementations in subclasses.

Provide better documentation, indicating to

programmer that subclass will implement them.

Page 57: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

57

ACARTESIANPLANE CONSTRUCTOR

public class ACartesianPlane implements CartesianPlane { int originX, originY; int axesLength; Line xAxis; Line yAxis; StringShape xLabel; StringShape yLabel; public ACartesianPlane (int theAxesLength, int theOriginX, int theOriginY ) { axesLength = theAxesLength; originX = theOriginX; originY = theOriginY; xAxis = new ALine(toXAxisX(), toXAxisY(), axesLength, 0); yAxis = new ALine(toYAxisX(), toYAxisY(), 0, axesLength); xLabel = new AStringShape ("X", toXLabelX(), toXLabelY()); yLabel = new AStringShape ("Y", toYLabelX(), toYLabelY()); }

Page 58: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

58

ANOBSERVABLE CARTESIANPLANE CONSTRUCTOR

Page 59: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

59

ACARTESIANPLANE

Page 60: COMP DYNAMIC DISPATCH AND ABSTRACT METHODSdewan/comp114/f12/Lectures/... · COMP 401 DYNAMIC DISPATCH AND ABSTRACT METHODS Instructor: Prasun Dewan

60

ANOBSERVABLE CARTESIANPLANE