CSE 501 N Fall 09 15 Polymorphism October

CSE 501 N Fall ‘ 09 15: Polymorphism October 22, 2009 Nick Leidenfrost

Lecture Outline n Lab 5 questions n Review: Inheritance n Polymorphism n Mid-semester review 2

Inheritance n Inheritance allows us to create more specific types from existing classes n This promotes: n ¨ Code Reuse ¨ Maintainability We can change the behavior that we inherit by: ¨ Overriding inherited methods ¨ Adding behavior via new members n Fields (Instance Variables) n Methods 3

Inheritance Design Issues (When should we use inheritance? ) n Every derivation should be an is-a relationship ¨ Child classes should define more specific behavior n Think about the potential future of a class hierarchy, and design classes to be reusable and flexible n Find common characteristics of classes and push them as high in the class hierarchy as appropriate n Override methods as needed to tailor or change the functionality of a subclass n Add new variables to children, but don't redefine (shadow) inherited variables, if possible 4

Inheritance Design Issues n Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data n Even if there are no current uses for them, override general methods such as to. String and equals with appropriate definitions n Use abstract classes to represent general concepts that lower classes have in common n Use visibility modifiers carefully to provide needed access without violating encapsulation 5

Polymorphism n Polymorphism is an object-oriented concept that allows us to create versatile software designs n We will look at on ¨ polymorphism and its benefits ¨ using inheritance to create polymorphic references ¨ using interfaces to create polymorphic references 6

Polymorphism n The term polymorphism literally means "having many forms" n A polymorphic reference is a variable that can refer to different types of objects at different points in time n The method invoked through a polymorphic reference can change from one invocation to the next n All object references in Java are potentially polymorphic 7

Binding n Consider the following method invocation: obj. do. Something(); n At some point, this invocation is bound to the definition of the method that it invokes n If this binding occurred at compile time, then that line of code would call the same method every time n However, Java defers method binding until run time n What we lose in predictability, we gain in program design flexibility 8

Polymorphism n Suppose we create the following reference variable: Animal animal; n Java allows this reference to point to an Animal object, or to any object of any compatible type n This compatibility can be established using inheritance or using interfaces n Careful use of polymorphic references can lead to elegant, robust software designs 9

Polymorphism n Consider an abstract class (or interface) Lender, meant to model a credit facility generally: public abstract class Lender { public abstract double borrow (double amount); public abstract double repay (double amount); public class Credit. Card extends Lender { //. . . } } public class Line. Of. Credit extends Lender { //. . . } 10

Polymorphism n A variable with an abstract class for a type holds reference to object of a class that extends Lender and implements its abstract methods. Lender x; x = new Credit. Card(); x = new Line. Of. Credit(); n Note that the object to which x refers doesn't have type Lender; the type of the object is some subclass of Lender. 11

Polymorphism n You can call any of the methods defined on the variable type: double remaining. Funds = x. borrow(1000); Which method is called? n The borrow method defined by the Line. Of. Credit class is called, because (per the previous slide) it is the current type stored inside variable x. n 12

Polymorphism n n Which method is invoked depends on the actual object referenced. If x refers to a Line. Of. Credit object, Java Invokes Line. Of. Credit’s borrow method If x refers to a Credit. Card object, Java invokes Credit. Card’s borrow method Behavior can vary depending on the actual type of an object stored in x ¨ However, notice that we are able to deal with x uniformly as a Lender regardless of what is actually stored inside 13

Polymorphism n Java doesn’t know at compile time what type of object is stored within a polymorphic variable ¨ So n how does it know what version of a method to call? It uses late binding: the method call is resolved at runtime ¨ a. k. a. n dynamic binding Different from overloading; overloading is resolved by the compiler (early binding) 14

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

Polymorphism via Interfaces n n Suppose two classes, Professor and Dog, both implement the Speaker interface, providing distinct Blah blah. versions of the speak method I’m really boring. In the following code, the first call to speak invokes Blah blah another: blah. one version and the second invokes Ruff. (Walk? Did you Speaker guest = new Professor(); say Walk? Treat? I guest. speak(); thought I heard “treat” guest = new Dog(); somewhere in there. ) guest. speak(); 16

References and Inheritance n An object reference can refer to an object of its class, or to an object of any class related to it by inheritance n For example if we have a Savings. Account object, then a variable of type Bank. Account could be used, if the Savings. Account class is derived from Bank. Account Savings. Account Bank. Account acct; . . . acct = new Savings. Account(); 17

Inheritance and Assignment n Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment Savings. Account savings = new Savings. Account(); Bank. Account account = savings; n Trust me Java, I know Assigning an parent object to a child reference can be done this is a also, but it is considered a narrowing conversion and must be Savings. Account done with a cast Bank. Account account = new Savings. Account(); Savings. Account savings = (Savings. Account)account; n The widening conversion is the most useful 18

Polymorphism n As we have seen, in Java, type of a variable doesn't definitively determine type of object to which it refers Bank. Account a. Bank. Account = new Savings. Account(1000); // a. Bank. Account holds a reference to a Savings. Account n Method calls are determined by type of actual object, not type of object reference Bank. Account an. Account = new Checking. Account(); an. Account. deposit(1000); // Calls "deposit" from Checking. Account 19

Polymorphism n Compiler needs to check that only legal methods are invoked Object an. Object = new Bank. Account(); //. . . an. Object. deposit(1000); // Compile-time Error! n Why is this not allowed? Object an. Object = new Bank. Account(); // Acceptable ways of casting: ((Bank. Account)an. Object). deposit(1000); Bank. Account account = (Bank. Account)an. Object; account. deposit(1000); 20

Polymorphism n n Polymorphism: ability to refer to objects of multiple types with varying behavior Polymorphism at work: public void transfer (double amount, Bank. Account other) { this. withdraw(amount); other. deposit(amount); } n Depending on types of amount and other, different versions of withdraw and deposit are called ¨ We don’t have to worry about the exact types we are working with 21

Polymorphism via Inheritance n Consider the following class hierarchy: Staff. Member Volunteer Employee Executive Hourly 22

Polymorphism via Inheritance n Now let's look at an example that pays a set of diverse employees using a polymorphic method [Example on board] 23

Conclusion I will be in Lab now for help with Lab 5 n Lab 6 will be assigned on Tuesday n ¨ (Enjoy your weekend) 24
- Slides: 24