Comp 401 Dynamic Dispatch and Virtual and Abstract Methods

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
C OMP 401 D YNAMIC D ISPATCH AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship –human IS-A.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
Inheritance and IS-A Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Multiple Inheritance, Factories, & Facades Prasun Dewan Comp 114.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Abstract Classes and Interfaces
Multiple Inheritance & Factories Prasun Dewan Comp 114.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance in the Java programming language J. W. Rider.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
C OMP 401 A DVANCED G ENERICS Instructor: Prasun Dewan.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
C OMP 401 D YNAMIC D ISPATCH AND V IRTUAL AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Instructor: Prasun Dewan
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Continuing Chapter 11 Inheritance and Polymorphism
Object Oriented Programming
Recitation 6 Inheritance.
CSC 143 Inheritance.
null, true, and false are also reserved.
Extending Classes.
Java Programming Language
Chapter 9: Polymorphism and Inheritance
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Java Inheritance.
Recitation 10 November 3, 2011.
Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
Chapter 11 Inheritance and Polymorphism Part 1
Topics OOP Review Inheritance Review Abstract Classes
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

Comp 401 Dynamic Dispatch and Virtual and Abstract Methods Instructor: Prasun Dewan

Prerequisite Inheritance Abstract Classes

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++;

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?

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

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

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); }

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); } Static dispatching: call most specific method known when caller method was compiled PointHistory pointHistory = new APolarPointHistoryWithDynamicallyDispatchedMethod(); pointHistory.addElement(50, 100); Dynamic dispatching: call most specific method for the calling object

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

Inheritance Relationships? APolarPointHistoryWithDynamicallyDispatchedMethod IS-A ACartesianPointHistoryWithDynamicallyDispatchedMethod ACartesianPointHistoryWithDynamicallyDispatchedMethod IS-A APolarPointHistoryWithDynamicallyDispatchedMethod

Correct Inheritance AnAbstractPointHistory IS-A IS-A ACartesianPointHistory APolarPointHistory

Correct Inheritance AnAbstractPointHistory IS-A IS-A ACartesianPointHistory APolarPointHistory

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?

Removing createPoint Compiler error 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++; Compiler error

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) {}

Overriding Dynamically Dispatched Method public class ACartesianPointHistory extends AnAbstractPointHistory{ protected Point createPoint(int x, int y) { return new ACartesianPoint(x, y); }

Erroneous Implementation with No Errors public class ACartesianPointHistory extends AnAbstractPointHistory{ }

Only header of method provided as in interface 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

Erroneous Implementation public class ACartesianPointHistory extends AnAbstractPointHistory{ } Java complains abstract method not implemented in concrete class

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.

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

Abstract class vs. methods Abstract method => containing class abstract Cannot have an unimplemented method in an instance Abstract class may not contain abstract method

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

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

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(); This means all sub classes implement the interface Interface implementation check is made for concrete classes An abstract class can implement any interface

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

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

When Abstract Method Required 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); Not public

Adding createPoint to Interface public interface PointHistoryWithExtraPublicMethod { public Point createPoint(int x, int y); } Factory method 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++; Concrete class guaranteed to implement it Least privilege violated

Factory Abstract Method … abstract <T> <M>(…) ; extends … <T> <M>(…) { return new <C1> (…) } … <T> <M> (…){ return new <C2> (…) } Abstract method that returns an instance of some type T – like a factory, it creates and initializes an object.

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!

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

Abstract methods vs. Virtual Methods Abstract methods must be virtual methods. Virtual methods need not be abstract methods

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 IS-A ACartesianPointHistoryWithDynamicallyDispatchedMethod

Overloading, Polymorphism, and Dynamic dispatch Polymorphic method ARegularCourse AFreshmanSeminar static void print (Course course) { System.out.println( course.getTitle() + " " + course.getDepartment() + course.getNumber() ); } static void print (CourseList courseList) { … print(course); Overloaded method getNumber() in ARegularCouse getNumber() in AFreshmanSeminar Dynamically dispatched method

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

Polymorphism vs. Overloading and Dynamic Dispatch 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

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.

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 ); } Must update code as subtypes added More Work

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

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: ”); Actual parameter cannot be supertype of formal parameter At compile time, do not know if regular course or freshman seminar

printHeader() in ARegularCourse package courses; public class ARegularCourse extends ACourse implements Course { … public void printHeader () { System.out.print (“Regular Course: ”) }

printHeader() in AFreshmanSeminar package courses; public class AFreshmanSeminar extends ACourse implements FreshmanSeminar { … public void printHeader () { System.out.print (“Freshman Seminar: ”) }

Should not 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: ”); Should not put printHeader() in ARegularCourse or AFreshmanSeminar as it is UI code. Hence need to use instanceof Used in parsers