1 CS2200 Software Development Lecture 29: Polymorphism I A. O’Riordan, 2008 Based on notes by K. Brown.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
1 SSD3 - Unit 2 Java toString & Equals Presentation Class Website:
Class Hierarchy (Inheritance)
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
1 CS2200 Software Development Polymorphism II A. O’Riordan, 2008 K. Brown,
 In inheritance the child (subclass) chooses its parent (superclass)  Remember - only public or “protected” methods and variables are inherited  Should.
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. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 Lecture 4 Further OO Concepts I - Polymorphism Overview  What is polymorphism?  Why polymorphism is wonderful?  Why is Upcasting useful?  What is.
Object-Orientated Design and Programming Unit 8: Inheritance and Polymorphism Jin Sa.
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism in Methods
Polymorphism.
Lecture 12 Inheritance.
Overriding Method.
CMPE212 – Stuff… Assn 3 due and Quiz 2 in the lab next week.
CSC 113 Tutorial QUIZ I.
Inheritance Basics Programming with Inheritance
Extending Classes.
CS18000: Problem Solving and Object-Oriented Programming
Computer Programming with JAVA
CISC124 Assignment 3 sample solution will be posted tonight after 7pm.
Inheritance.
Java Programming: From the Ground Up
Presentation transcript:

1 CS2200 Software Development Lecture 29: Polymorphism I A. O’Riordan, 2008 Based on notes by K. Brown

2 Inheritance Review ●inheritance allows us to re-use classes by specialising them ●we can build class hierarchies using the keyword extends ●each child (subclass) inherits all the data and methods of its parent (superclass) ●we can add new methods in the subclass, or override the inherited methods ●private data and methods are inherited, but cannot be accessed by other classes; protected data and methods can be accessed by child classes ●constructor methods must be invoked in the first line in a subclass constructor as a call to super

3 Inheritance: Example all the Entry methods and data are inherited by every object in the Website and Person classes Website url getUrl() Person phone getPhone() get () Consider an address book that has two different types of entry: 1.Website with a URL 2.Person with a Phone number and Entry name getName() e.g. public class Person extends Entry { … }

4 What objects of the subclass look like person1: Person name: Jim phone: data that have been inherited from the Entry object

5 Polymorphism ●many forms (from Greek) ●the ability of an object (or reference) to assume (be replaced by) or become many different forms of object (possibly satisfying some implicit or explicit type constraints or a common structure) ●Interchanging superclass and subclass ●A subclass object is an object of the superclass ●We can create an object of the subclass, and then refer to it using a reference to the superclass ●This allows us to work with objects of different but related classes in a consistent way ●But if we do this, (simplistically) we are only able to use attributes and behaviours defined at or above the superclass level

6 Example: Simple address book Suppose an address book maintains an array of all entries. Some of the entries are websites, while some are people. We can declare an array of Entry objects. Each time we create a Website or Person, we add a reference to it into the array. We can then treat each entry uniformly. public class Entry { private String name; public Entry(String n) { name = n; } public String getName() { return name; }

public class Website extends Entry { private String url; public Website(String n, String u) { super(n); url = u; } public String getUrl() { return url; } }

public class Person extends Entry { private String phone; private String ; public Person(String n, String p, String e) { super(n); phone = p; = e; } public String getPhone() { return phone; } public String get () { return ; } }

public class SimpleAddressBook { private Entry[] book; //the array of entries private int nextEntry; //index of next available cell //Constructor - no arguments public SimpleAddressBook() { book = new Entry[10]; nextEntry = 0; } //run the Address Book "GUI" public void process() { String menu = "0: add entry; 1: display names; -1: quit"; String choiceStr = JOptionPane.showInputDialog (menu); int choice = Integer.parseInt(choiceStr); while (choice > -1) { if (choice == 0) addEntry(); else if (choice == 1) displayNames(); choiceStr = JOptionPane.showInputDialog (menu); choice = Integer.parseInt(choiceStr); }

public void addEntry() { if (nextEntry < book.length) { String name, phone, url, ; String menu = "0: website; 1: person; -1: none"; String choiceStr = JOptionPane.showInputDialog (menu); int choice = Integer.parseInt(choiceStr); switch(type) { case 0: name = JOptionPane.showInputDialog ("Name:"); url = JOptionPane.showInputDialog ("URL:"); book[nextEntry] = new Website(name, url); nextEntry++; break; case 1: name = JOptionPane.showInputDialog ("Name:"); phone = JOptionPane.showInputDialog ("Phone:"); = JOptionPane.showInputDialog (" "); book[nextEntry] = new Person(name, phone, ); nextEntry++; break; default: JOptionPane.showMessageDialog("No entry added"); } else JOptionPane.showMessageDialog("No space left"); } Entry reference Entry reference Person object Person object

public void displayNames() { String str = "Names:\n"; for (int i = 0; i<book.length; i++) if (book[i] != null) str = str + i + ": " + book[i].getName() + "\n"; JOptionPane.showMessageDialog(str); } public static void main(String[] args) { SimpleAddressBook sab = new SimpleAddressBook(); sab.process(); System.exit(0); } Entry reference, invoking an Entry method, but it may be a Person or Website object

12 We have added the new objects directly into the array as they are created... book[nextEntry] = new Person(name, phone, ); which means we cannot easily use the Person methods, since we have no Person reference (only an Entry reference). If we try book[i].getPhone() Java will say that book[i] refers to an Entry object, which has no such method! Accessing the subclass methods

13 Casting superclass to subclass If we know that a reference is actually to an object of a particular subclass, then we can cast the reference to the subclass, and access its methods. ((Website)book[2]).getUrl() ; the cast brackets, so that getUrl() is not invoked until we have cast book[2] to the Website class book[2] is an Entry reference, but if we know it really points to a Website object, we can tell Java using the cast, and we can then invoke the getUrl() method But casts put the onus on the programmer

14 AddressBook: overriding display() Instead we will use method overriding public class Entry { public String name; //the name associated with the entry //display() - will be overriden public String display() { return name; }... } Define display() at the Entry level. We don't expect this to be executed, since all subclasses should define their own version, but (for now) we still need default behaviour here

15 overriding display() - continued public class Website extends Entry { public String url;... //convert the whole entry to a display string //overrides Entry.display() public String display() { String output = "(Website)\n" + " name: " + name + "\n" + " url: " + url + "\n" + return output; }... } We just simply define the method at the lower level as normal

16 invoking display() //display the requested contents on new lines String str = ""; for (int i = 0; i < lastEntry; i++) str = str + i + ": " + book[i].display(); No need for casts! The method display() in the Entry class is polymorphic - it has different forms depending on which subclass is used. When we invoke the display() method, Java will choose the correct method at run-rime - i.e. it binds the call to a method implementation dynamically.