Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 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 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 email getPhone() getEmail() Consider an address book that has two different types of entry: 1.Website with a URL 2.Person with a Phone number and email Entry name getName() e.g. public class Person extends Entry { … }

4 4 What objects of the subclass look like person1: Person name: Jim phone: 555-5050505 email: jim@bob.com data that have been inherited from the Entry object

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

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

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

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

10 public void addEntry() { if (nextEntry < book.length) { String name, phone, url, email; 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:"); email = JOptionPane.showInputDialog ("Email:"); book[nextEntry] = new Person(name, phone, email); nextEntry++; break; default: JOptionPane.showMessageDialog("No entry added"); } else JOptionPane.showMessageDialog("No space left"); } Entry reference Entry reference Person object Person object

11 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 12 We have added the new objects directly into the array as they are created... book[nextEntry] = new Person(name, phone, email); 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 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 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 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 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.


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

Similar presentations


Ads by Google