1 / 33

Polymorphism

Polymorphism. Abstract Classes. Java allows abstract classes use the modifier abstract on a class header to declare an abstract class abstract class Vehicle { … } An abstract class is a placeholder in a class hierarchy that represents a generic concept. Vehicle. Car. Boat. Plane.

aya
Download Presentation

Polymorphism

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Polymorphism

  2. Abstract Classes • Java allows abstract classes • use the modifier abstract on a class header to declare an abstract classabstract class Vehicle{ … } • An abstract class is a placeholder in a class hierarchy that represents a generic concept Vehicle Car Boat Plane

  3. Abstract Class: Example • An abstract class often contains abstract methods, though it doesn’t have to • Abstract methods consist of only methods declarations, without any method body public abstract class Vehicle { String name; public String getName() { return name; } \\ method body abstract public void move(); \\ no body! }

  4. Abstract Classes • An abstract class often contains abstract methods, though it doesn’t have to • Abstract methods consist of only methods declarations, without any method body • The non-abstract child of an abstract class must override the abstract methods of the parent • An abstract class cannot be instantiated (why?) • The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate

  5. Recap: References and Inheritance • An object reference variable can refer to any object instantiated from • its own class, or • any class derived from it by inheritance • For example, Holiday day; day = new Holiday(); … day = new Christmas(); Holiday Christmas The assignment of an object of a derived class to a reference variable of the base class can be considered as a widening conversion

  6. References and Inheritance • Through a given type of reference variable, we can invoke only the methods defined in that type class Holiday{ public void celebrate() {…}} class Christmas extends Holiday{ public void celebrate() {…} public void listenToChristmasSongs() {…} } Holiday day; day = new Christmas(); Can we do the following statements: day.celebrate(); day.listenToChristmasSongs();

  7. References and Inheritance • We can “promote” an object back to its original type through an explicit narrowing cast: Holiday day = new Christmas(); day.celebrate(); … Christmas c = (Christmas) day; c.listenToChristmasSongs(); Question: which celebrate() will be invoked by the line: day.celebrate();

  8. Java Interface • A Java interface is a collection of constants and abstract methods • abstract method: a method header without a method body; we declare an abstract method using the modifier abstract • since all methods in an interface are abstract, the abstract modifier is usually left off • Methods in an interface have public visibility by default

  9. interface is a reserved word A semicolon immediately follows each method header Interface: Syntax public interface Doable { public static final String NAME; public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } No method in an interface has a definition (body)

  10. Implementing an Interface • A class formally implements an interface by • stating so in the class header in the implements clause • a class can implement multiple interfaces: the interfaces are listed in the implements clause, separated by commas • If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors

  11. implements is a reserved word Each method listed in Doable is given a definition Implementing Interfaces public class Something implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } public class ManyThings implements Doable, AnotherDoable

  12. Interfaces: Examples from Java Standard Class Library • The Java Standard Class library defines many interfaces: • the Iterator interface contains methods that allow the user to move through a collection of objects easily • hasNext(), next(), remove() • the Comparable interface contains an abstract method called compareTo, which is used to compare two objects if (obj1.compareTo(obj2) < 0) System.out.println(“obj1 is less than obj2”);

  13. Polymorphism via Interfaces • Define a polymorphism reference through interface • declare a reference variable of an interface typeDoable obj; • the obj reference can be used to point to any object of any class that implements the Doable interface • the version of doThis depends on the type of object that obj is referring to: obj.doThis();

  14. Interface Hierarchies • Inheritance can be applied to interfaces as well as classes • One interface can be used as the parent of another • The child interface inherits all abstract methods of the parent • A class implementing the child interface must define all methods from both the parent and child interfaces • Note that class hierarchies and interface hierarchies are distinct (they do not overlap)

  15. Scenarios • A veterinarian's algorithm might have a list of animals, but each one needs different food or care… we want ONE information system to track all of this without complex logic for each individual kind of animal. • A car dealership sells many different types of cars with different features, but each has a price and quantity in stock. • A registration system might treat in-state students differently from out-of-state students, graduate students differently from undergraduates, etc. • A graphical user interface (GUI) e.g. Windows needs to puts lots of simlar widgets on screen... LB

  16. Motivation • We’d like to be able to manage objects of different kinds of classes. • Since classes within a class hierarchy often share common methods and attributes, we’d like to make use of this fact to make our algorithms simpler.

  17. Polymorphism Defined • The ability to take on different forms. • Manipulate objects of various classes, and invoke methods on an object without knowing that object’s type.

  18. A Class Hierarchy Animal Dog Cat Fish Mutt Poodle Gold Beta

  19. A Polymorphic Example Animal Dog MyMutt isoftype Mutt MyAnimal isoftype Animal MyDog isoftype Dog . . . MyDog <- MyMutt MyAnimal <- MyMutt Mutt

  20. Polymorphism Explained MyAnimal <- MyMutt seems incorrect. The left and right hand side of the assignment seem to not match; or do they? Since Mutt inherits from Dog, and Dog inherits from Animal, then MyMutt is at all times a Mutt, a Dog, and an Animal. Thus the assignment statement is perfectly valid. This makes logical (“real world”) sense.

  21. An Illegal Example • We are able to assign an object of a sub-class into an object of a super-class as in: MyAnimal <- MyMutt • But the reverse is not true. We can’t assign a superclass object into a sub-class object. MyMutt <- MyAnimal // illegal

  22. Method Calls and Polymorphism Assume the Dog class inherits the Animal class, redefining the “MakeNoise” method. Consider the following: MyAnimal <- MyDog MyAnimal.MakeNoise

  23. Method Calls and Polymorphism MyAnimal <- MyDog MyAnimal.MakeNoise Different languages handle this differently. For simplicity, we’ll assume that MyAnimal “remembers” it is actually an object of the Dog class, so we’ll execute the MakeNoise method in the Dog class.

  24. Polymorphism vs. Inheritance • Inheritance is required in order to achieve polymorphism (we must have class hierarchies). • Re-using class definitions via extension and redefinition • Polymorphism is not required in order to achieve inheritance. • An object of class A acts as an object of class B (an ancestor to A).

  25. Processing Collections • One of the main benefits of polymorphism is the ability to easily process collections. • We will consider a collection (queue) of bank accounts in the next example. . .

  26. Bank Account Savings Account Checking Account NOW Account Cool Savings Money Market Account CD Account The Banking Class Hierarchy

  27. A Collection of Bank Accounts Imagine a bank needs to manage all of the accounts. Rather than maintain seven separate queues, one each for: Bank_Accounts, Savings_Accounts, Cool_Savings, CD_Accounts, Checking_Accounts, NOW_accounts, and Money_Market_Accounts We can maintain only one queue of Bank Accounts.

  28. Polymorphic Banking Assume accounts of various kinds: john_account isoftype Checking_Account paul_account isoftype Cool_Savings paul_other_account isoftype CD_Account george_account isoftype NOW_Account ringo_account isoftype Money_Market Then put them all in a single structure: account_queue isoftype Queue(Bank_Account) account_queue.Enqueue(john_account) account_queue.Enqueue(paul_account) account_queue.Enqueue(paul_other_account) account_queue.Enqueue(george_account) account_queue.Enqueue(ringo_account)

  29. Polymorphic Banking • account_queue is polymorphic: • It is holding accounts of “many forms.” • Each of the accounts is “within the family” of the class hierarchy of bank accounts. • Each one will have it’s own set of capabilities via inheritance (extension, and/or redefinition).

  30. Resolving Polymorphic Method Calls • Different languages do this differently. • The various kinds of Accounts, though all stored as a Bank_Account, remember the class (subclass) of which they are an instance. • So, calls to Get_Balance() will: • use the method from class NOW_Account if the object is an instance of NOW_Account • use the method from class Money_Market if the object is an instance of Money_Market • and so on...

  31. Polymorphism • This is the “magic” of polymorphism…it keeps track of family members within the inheritance hierarchy for you. • Without it, we’d have lots of code sprinkled through out our algorithm choosing among many options: • if( it’s Checking_Account ) then • call Checking_Account Calc_Interest • elseif( it’s Super_Savings) then • call Super_Savings Calc_Interest • elseif( it’s CD_Account then • call CD_Account Calc_Interest • elseif( it’s NOW_Account ) then • call NOW_Account Calc_Interest • . . .

  32. Summary • Polymorphism allows objects to represent instances of its own class and any of its sublcasses. • Polymorphic collections are useful for managing objects with common (ancestor) interfaces. • For our purposes, we’ll assume objects “remember” what kind of class they really contain, so method calls are resolved to the original class.

  33. Explain how you would program this

More Related