C OMP 401 D YNAMIC D ISPATCH AND A BSTRACT M ETHODS Instructor: Prasun Dewan.

Slides:



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

Object Oriented Programming
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.
C OMP 110/401 C OLLECTION K INDS Instructor: Prasun Dewan.
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 110 A RRAYS Instructor: Jason Carter. 2 O UTLINE for loops Arrays.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
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.
Arrays –Collections (Set, Database, History) Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables)
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.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Multiple Inheritance, Factories, & Facades Prasun Dewan Comp 114.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
Abstract Classes b b An abstract class is a placeholder in a class hierarchy that represents a generic concept b b An abstract class cannot be instantiated.
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.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance Inheritance is the process of extending the functionality of a class by defining a new class that inherit,all the features of extending class.
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 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)
CH10 Supplementary Material Prepared by Fatimah Alakeel Oct 2010.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
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
Inheritance and Polymorphism
Comp 401 Dynamic Dispatch and Virtual and Abstract Methods
Object Oriented Programming
Java Programming Language
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Recitation 7 October 7, 2011.
Java Inheritance.
Recitation 10 November 3, 2011.
CIS 199 Final Review.
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

C OMP 401 D YNAMIC D ISPATCH AND A BSTRACT M ETHODS Instructor: Prasun Dewan

2 A S TRING H ISTORY I MPLEMENTATION 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++; }

3 A B IG S TRING H ISTORY I MPLEMENTATION 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++; }

4 N ULL O VERRIDDEN M ETHOD 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"); }; }

5 A S TRING H ISTORY I MPLEMENTATION 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++; }

6 D YNAMIC D ISPATCH 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()

7 R EGULAR VS. V IRTUAL M ETHOD 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

8 C ORRECT A B IG S TRING H ISTORY I MPLEMENTATION 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++; }

9 A N E RRONEOUS B IG S TRING H ISTORY I MPLEMENTATION 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++; //} }

10 N ULL O VERRIDDEN M ETHOD 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"); }; }

11 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

12 A N E RRONEOUS B IG S TRING H ISTORY I MPLEMENTATION 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

13 N ULL VS. A BSTRACT M ETHODS 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.

14 A BSTRACT 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).

15 A BSTRACT CLASS VS. METHODS Abstract method => containing class abstract Cannot have an unimplemented method in an instance Abstract class may not contain abstract method

16 A BSTRACT C LASS 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"); }; }

17 C ONCRETE C LASS public class ABigStringHistory extends AnAbstractStringHistory 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; } void uncheckedAddElement(String element) { contents[size] = element; size++; } Move more code to abstract class?

18 N EW A BSTRACT C LASS public class AnAbstractStringHistory implements StringHistory { String[] contents = new String[maxSize()]; int size = 0; abstract int maxSize(); public int size() { return size;} public String elementAt ( int index) { return contents[index]; } boolean isFull() { return size == maxSize(); } public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; }

19 public class ABigStringHistory extends AnAbstractStringHistory implements StringHistory { public static final int MAX_SIZE = 500; int maxSize() { return MAX_SIZE; } N EW C ONCRETE C LASS Method call needed to access constant

20 A NOTHER C OURSE package courses; 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(); } Abstract Method

21 A LTERNATIVE AR EGULAR C OURSE package courses; 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; } Implementation of abstract method Like interface, force implementation of getNumber()

22 A LTERNATIVE AF RESHMAN S EMINAR package courses; public class AFreshmanSeminar extends ACourse { public AFreshmanSeminar (String theTitle, String theDept) { super (theTitle, theDept); } public int getNumber() { return SEMINAR_NUMBER; } Implementation of abstract method

23 A BSTRACT C LASS 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"); }; } Not public

24 F ACTORY A BSTRACT M ETHOD … abstract (…) ; … abstract (…) ; … (…) { return new (…) } … (…) { return new (…) } … extends … (…){ return new (…) } … (…){ return new (…) } … Abstract method that returns an instance of some type T – like a factory, it creates and initializes an object.

25 A BSTRACT METHODS VS. I NTERFACES 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!

26 A BSTRACT METHODS VS. I NTERFACES 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() ;

27 A NOTHER C OURSE 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; } An abstract class can implement any interface This means all sub classes implement the interface Interface implementation check is made for concrete classes

28 A LTERNATIVE AR EGULAR C OURSE package courses; 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

29 A LTERNATIVE AF RESHMAN S EMINAR package courses; 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

30 O VERLOADING, P OLYMORPHISM, AND D YNAMIC 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

31 O VERLOADING, P OLYMORPHISM, AND D YNAMIC 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

32 P OLYMORPHISM VS. O VERLOADING AND D YNAMIC D ISPATCH 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

33 P OLYMORPHISM VS. O VERLOADING AND D YNAMIC D ISPATCH 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.

34 M ANUAL INSTEAD OF D YNAMIC D ISPATCH 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

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

36 C ANNOT 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

37 PRINT H EADER () IN AR EGULAR C OURSE package courses; public class ARegularCourse extends ACourse implements Course { … public void printHeader () { System.out.print (“Regular Course: ”) }

38 PRINT H EADER () IN AF RESHMAN S EMINAR package courses; public class AFreshmanSeminar extends ACourse implements FreshmanSeminar { … public void printHeader () { System.out.print (“Freshman Seminar: ”) }

39 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: ”); } S HOULD 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

40 E XTRA S LIDES