1 Advanced Polymorphism Polymorphism Review Comparator Interface Sorting with Comparators Selection Sort Insertion Sort.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Advertisements

IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 9: Polymorphism Coming up: Binding.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved9-2 Polymorphism Polymorphism (having many forms) is an object- oriented concept.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
1 Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 9.1 – 9.3.
8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Abstract Classes.
1 Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter Day 22. © 2007 Pearson Addison-Wesley. All rights reserved Agenda Day 22 Problem set 4 Posted  10 problems from chapters 7 & 8  Due Nov 21 (right.
ECE122 L22: Polymorphism Using Inheritance April 26, 2007 ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Inheritance.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
CS 106 Introduction to Computer Science I 04 / 21 / 2008 Instructor: Michael Eckmann.
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
Aalborg Media Lab 15-Jul-15 Polymorphism Lecture 12 Chapter 9.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Polymorphism  A reference can be polymorphic, which can be defined as "having many forms" obj.doIt();  This line of code might execute different methods.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Do Now Take out ch6 test answers – be ready to hand it in Pick a leader in each group of up to 3 students; Leader will retrieve a whiteboard, marker, and.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Chapter 9: Polymorphism Coming up: Creating Objects Revisited.
Chapter 9 – Part 2 Polymorphism: Sorting & Searching.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
© 2004 Pearson Addison-Wesley. All rights reserved April 17, 2006 Polymorphism (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Comparison-Based Sorting & Analysis Smt Genap
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
ELC 310 Day 19. © 2004 Pearson Addison-Wesley. All rights reserved9-2 Agenda Questions? Capstone Proposals Overdue  4 Submitted  3 Accepted, 1 in negotiations.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Sorting b Sorting is the process of arranging a list of items into a particular order b There must be some value on which the order is based b There.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Chapter 9 – Part 2 Polymorphism: Sorting & Searching.
Searching and Sorting Searching algorithms with simple arrays
Chapter 9: Sorting and Searching Arrays
Polymorphism November 27, 2006 ComS 207: Programming I (in Java)
Chapter 9 Polymorphism.
Polymorphism.
Designing for Inheritance
Sorts.
Data Structures and Algorithms
Outline Late Binding Polymorphism via Inheritance
Chapter 9 Polymorphism.
Sorting and Searching -- Introduction
Arrays.
Presentation transcript:

1 Advanced Polymorphism Polymorphism Review Comparator Interface Sorting with Comparators Selection Sort Insertion Sort

Polymorphism The term polymorphism literally means "having many forms" A polymorphic reference is a variable that can refer to different types of objects at different points in time All object references in Java are potentially polymorphic and can refer to an object of any type compatible with its defined type Compatibility of class types can be based on either Inheritance or Interface

Polymorphism Suppose we create the following object reference variable ( Holiday can be a class or an interface): Holiday day; Java allows this reference to point to a Holiday object or to any object of any compatible type If class Christmas extends Holiday or if class Christmas implements Holiday, a Christmas object is a compatible type with a Holiday object and a reference to one can be stored in the reference variable day: day = new Christmas();

References and Inheritance An object reference can refer to an object of its class or to an object of any class related to it by inheritance For example, if the Christmas class extends the Holiday class, then a Holiday reference could be used to refer to a Christmas object Holiday day; day = new Christmas(); Holiday Christmas

References and Inheritance Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment The widening conversion is the most useful Assigning an parent object to a child reference can be done, but it is considered a narrowing conversion and two rules/guidelines apply: –A narrowing conversion must be done with a cast –A narrowing conversion should only be used to store an object back to or toward its original class (back to what it was “born as”)

Polymorphism via Inheritance It is the type of the object being referenced, not the reference type, that determines which method is invoked If the Holiday class has a celebrate method, and the Christmas class overrides it, consider the following invocation: day.celebrate(); If day refers to a Holiday object, it invokes the Holiday version of celebrate() If day refers to a Christmas object, it invokes the Christmas version of celebrate()

Polymorphism via Inheritance Holiday ChristmasNewYearThanksgiving Holiday day; Christmas xmas = new Christmas(); day = xmas; // widening conversion (no cast needed) NewYear auldLangSyne = new NewYear(); day = auldLangSyne; // widening conversion (no cast needed) Thanksgiving turkey = (Thanksgiving) day; // not back to what it was “born as” // however, compiler accepts cast // will cause a run time exception

References and Interfaces An object reference can refer to an object of its class or to an object of any class related to it by an interface For example, if a Christmas class implements Holiday, then a Holiday reference could be used to point to a Christmas object Holiday day; day = new Christmas(); Holiday Christmas

Polymorphism via Interfaces An interface name can be used as the type of an object reference variable Speaker current; The current reference can be used to point to any object of any class that implements the Speaker interface The version of speak that the following line invokes depends on the type of object that current is referencing current.speak();

Polymorphism via Interfaces Suppose two classes, Philosopher and Dog, both implement the Speaker interface, but each provides a distinct version of the speak method In the following code, the first call to speak invokes the Philosopher method and the second invokes the Dog method: Speaker guest = new Philosopher(); guest.speak(); guest = new Dog(); guest.speak();

Summary of Polymorphism public class Christmas extends Holiday implements Observable, Ignorable { // code here } Holiday APIIgnorable APIObservable API Christmas API Object of class Christmas Why only one class name here?

Summary of Polymorphism Object instantiated as:Can/Cannot be cast: Child or Later Descendent Class To Parent or Earlier Ancestor (and back to its original class) Parent or Earlier Ancestor Class Any Class To any Interface it implements (and back to its original class) To Child or Later Descendent Any Interface (Not Allowed) To any “incompatible class”

Polymorphism: UML Class Diagrams You see how both Inheritance and Interfaces can be used to support polymorphic object references You should now be able to understand why both Inheritance and Interfaces are shown with the same “generalization” arrow icon in UML class diagrams Any Class Parent Class (Extends) Any Class Interface (Implements)

Comparator Interface 14 Comparator Interface requires two methods: int compare (T thisOne, T thatOne) boolean equals (Object o) Usually we only care about the compare method Returns an int value that is: Negative when “this” object is less than “that” object Zero when “this” object is equal to “that” object Positive when “this” object is greater than “that” object We can have multiple Comparator classes - one for each useful ordering of the specific object type It is safe to not override the Object class equals

Comparator Interface import java.util.Comparator; public class CompareAlpha implements Comparator { public int compare(String thisOne, String thatOne) { return thisOne.compareTo(thatOne); } public static void main(String [ ] args) { CompareAlpha ca = new CompareAlpha(); ca.go(ca); // rest of main is in go } private void go(Comparator c) { System.out.println(c.compare("Hello","World")); // returns -15 }

Comparator Interface import java.util.Comparator; public class CompareLength implements Comparator { public int compare(String thisOne, String thatOne) { return thisOne.length() - thatOne.length(); } public static void main(String [] args) { CompareLength cl = new CompareLength(); cl.go(cl); // rest of main is in go } private void go(Comparator c) { System.out.println(c.compare("Hello","World")); // returns 0 (zero) }

Comparator Interface Project 2 needs three Comparator classes Comparators will compare “County” objects: import java.util.Comparator; public class PopulationComparator implements Comparator { public int compare(County thisOne, County thatOne) { // calculate and return an integer here }

Sorting with Comparator(s) public void actionPerformed (ActionEvent e) {... // Figure out which Comparator to use based on radio buttons MySorts sorter; if ( population.isSelected() ) sorter = new MySorts ( new PopulationComparator() ); else if ( state.isSelected() ) sorter = new MySorts ( new StatePopulationComparator() ); else sorter = new MySorts ( new NameComparator() );

Sorting with Comparator(s) // Figure out which sort method to use if ( insertion.isSelected() ) sorter.insertionSort( array ); else sorter.selectionSort( array ); disp.reset( array ); // now show it }

Sorting with Comparator(s) public class MySorts { Comparator comp; public MySorts( Comparator comp ) { this.comp = comp; } // Swaps two Type T objects in the array private void swap( T [ ] o, int i, int j ) { T temp = o[i]; o[i] = o[j]; o[j] = temp; }

Selection Sort The approach of Selection Sort: –Select a value and put it in its final place in the list –Repeat for all other values In more detail: –Find the smallest value in the list –Switch it with the value in the first position –Find the next smallest value in the list –Switch it with the value in the second position –Repeat until all values are in their proper places

Selection Sort An example: original: smallest is 1: smallest is 2: smallest is 3: smallest is 6: Each time, the smallest remaining value is found and exchanged with the element in the "next" position to be filled

Sorting with Comparator(s) public void selectionSort( T [ ] o ) { int min; for (int index = 0; index < o.length-1; index++) { min = index; for (int scan = index+1; scan < o.length; scan++) if ( comp.compare( o[scan], o[min]) < 0 ) min = scan; swap( o, index, min ); }

Insertion Sort The approach of Insertion Sort: –Pick any item and insert it into its proper place in a sorted sublist –Repeat until all items have been inserted In more detail: –Consider the first item to be a sorted sublist (of one item) –Insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new addition –Insert the third item into the sorted sublist (of two items), shifting items as necessary –Repeat until all values are inserted into their proper positions

Insertion Sort An example: insert 9: insert 6: insert 3: insert 2: finished:

Sorting with Comparator(s) public void insertionSort( T [ ] o ) { for ( int index = 1; index < o.length; index++ ) { T key = o[index]; int position = index; // shift larger values to the right while (position>0 && comp.compare( o[position-1], key ) > 0) { o[position] = o[position-1]; position--; } o[position] = key; }