1、Object Oriented Programming using Java- Polymorphism,Dale Roberts, LecturerComputer Science, IUPUIE-mail: drobertscs.iupui.edu,Department of Computer and Information Science,School of Science, IUPUI,2,10.1Introduction,PolymorphismEnables “programming in the general”The same invocation can produce “m
2、any forms” of resultsInterfacesImplemented by classes to assign common functionality to possibly unrelated classes,3,10.2Polymorphism Examples,PolymorphismWhen a program invokes a method through a superclass variable, the correct subclass version of the method is called, based on the type of the ref
3、erence stored in the superclass variableThe same method name and signature can cause different actions to occur, depending on the type of object on which the method is invokedFacilitates adding new classes to a system with minimal modifications to the systems code,4,10.3Demonstrating Polymorphic Beh
4、avior,A superclass reference can be aimed at a subclass objectThis is possible because a subclass object is a superclass object as wellWhen invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is calledA subclass refe
5、rence can be aimed at a superclass object only if the object is downcasted,5,Outline,PolymorphismTest.java(1 of 2),Typical reference assignments,6,Outline,PolymorphismTest.java(2 of 2),Assign a reference to a basePlusCommissionEmployee object to a CommissionEmployee3 variable,Polymorphically call ba
6、sePlusCommissionEmployees toString method,7,Abstract Classes and Methods,Abstract classesClasses that are too general to create real objectsUsed only as abstract superclasses for concrete subclasses and to declare reference variablesMany inheritance hierarchies have abstract superclasses occupying t
7、he top few levelsKeyword abstractUse to declare a class abstractAlso use to declare a method abstractAbstract classes normally contain one or more abstract methodsAll concrete subclasses must override all inherited abstract methods,8,10.4Abstract Classes and Methods (Cont.),Iterator classTraverses a
8、ll the objects in a collection, such as an arrayOften used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchy,9,Fig. 10.2 | Employee hierarchy UML class diagram.,10,Software Engineering Observation 10.4,A subclass can inherit “i
9、nterface” or “implementation” from a superclass. Hierarchies designed for implementation inheritance tend to have their functionality high in the hierarchyeach new subclass inherits one or more methods that were implemented in a superclass, and the subclass uses the superclass implementations. (cont
10、),11,Software Engineering Observation 10.4,Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchya superclass specifies one or more abstract methods that must be declared for each concrete class in the hierarchy, and the individual subclasses override
11、these methods to provide subclass-specific implementations.,12,Creating Abstract Superclass Employee,abstract superclass Employeeearnings is declared abstractNo implementation can be given for earnings in the Employee abstract classAn array of Employee variables will store references to subclass obj
12、ectsearnings method calls from these variables will call the appropriate version of the earnings method,13,Fig. 10.3 | Polymorphic interface for the Employee hierarchy classes.,14,Outline,Employee.java(1 of 3),Declare abstract class Employee,Attributes common to all employees,15,Outline,Employee.jav
13、a(2 of 3),16,Outline,Employee.java(3 of 3),abstract method earnings has no implementation,17,Outline,SalariedEmployee.java(1 of 2),Class SalariedEmployee extends class Employee,Call superclass constructor,Validate and set weekly salary value,Call setWeeklySalary method,18,Outline,SalariedEmployee.ja
14、va(2 of 2),Override earnings method so SalariedEmployee can be concrete,Override toString method,Call superclasss version of toString,19,Outline,HourlyEmployee.java(1 of 2),Class HourlyEmployee extends class Employee,Call superclass constructor,Validate and set hourly wage value,20,Outline,HourlyEmp
15、loyee.java(2 of 2),Validate and set hours worked value,Override earnings method so HourlyEmployee can be concrete,Override toString method,Call superclasss toString method,21,Outline,CommissionEmployee.java(1 of 3),Class CommissionEmployee extends class Employee,Call superclass constructor,Validate
16、and set commission rate value,22,Outline,CommissionEmployee.java(2 of 3),Validate and set the gross sales value,23,Outline,CommissionEmployee.java(3 of 3),Override earnings method so CommissionEmployee can be concrete,Override toString method,Call superclasss toString method,24,Outline,BasePlusCommi
17、ssionEmployee.java(1 of 2),Class BasePlusCommissionEmployee extends class CommissionEmployee,Call superclass constructor,Validate and set base salary value,25,Outline,BasePlusCommissionEmployee.java(2 of 2),Override earnings method,Call superclasss earnings method,Override toString method,Call super
18、classs toString method,26,Outline,PayrollSystemTest.java(1 of 5),27,Outline,PayrollSystemTest.java(2 of 5),Assigning subclass objects to supercalss variables,Implicitly and polymorphically call toString,28,Outline,PayrollSystemTest.java(3 of 5),If the currentEmployee variable points to a BasePlusCom
19、missionEmployee object,Downcast currentEmployee to a BasePlusCommissionEmployee reference,Give BasePlusCommissionEmployees a 10% base salary bonus,Polymorphically call earnings method,Call getClass and getName methods to display each Employee subclass objects class name,29,Outline,PayrollSystemTest.
20、java(4 of 5),30,Outline,PayrollSystemTest.java(5 of 5),Same results as when the employees were processed individually,Base salary is increased by 10%,Each employees type is displayed,31,10.5.7Summary of the Allowed Assignments Between Superclass and Subclass Variables,Superclass and subclass assignm
21、ent rulesAssigning a superclass reference to a superclass variable is straightforwardAssigning a subclass reference to a subclass variable is straightforwardAssigning a subclass reference to a superclass variable is safe because of the is-a relationshipReferring to subclass-only members through supe
22、rclass variables is a compilation errorAssigning a superclass reference to a subclass variable is a compilation errorDowncasting can get around this error,32,10.6final Methods and Classes,final methodsCannot be overridden in a subclassprivate and static methods are implicitly finalfinal methods are
23、resolved at compile time, this is known as static bindingCompilers can optimize by inlining the codefinal classesCannot be extended by a subclassAll methods in a final class are implicitly final,33,Performance Tip 10.1,The compiler can decide to inline a final method call and will do so for small, s
24、imple final methods. Inlining does not violate encapsulation or information hiding, but does improve performance because it eliminates the overhead of making a method call.,34,In the Java API, the vast majority of classes are not declared final. This enables inheritance and polymorphismthe fundament
25、al capabilities of object-oriented programming. However, in some cases, it is important to declare classes finaltypically for security reasons.,Software Engineering Observation 10.6,35,10.7Case Study: Creating and Using Interfaces,InterfacesKeyword interfaceContains only constants and abstract metho
26、dsAll fields are implicitly public, static and finalAll methods are implicitly public abstract methodsClasses can implement interfacesThe class must declare each method in the interface using the same signature or the class must be declared abstractTypically used when disparate classes need to share
27、 common methods and constantsNormally declared in their own files with the same names as the interfaces and with the .java file-name extension,36,Good Programming Practice 10.1,According to Chapter 9 of the Java Language Specification, it is proper style to declare an interfaces methods without keyw
28、ords public and abstract because they are redundant in interface method declarations. Similarly, constants should be declared without keywords public, static and final because they, too, are redundant.,37,Common Programming Error 10.6,Failing to implement any method of an interface in a concrete cla
29、ss that implements the interface results in a syntax error indicating that the class must be declared abstract.,38,10.7.1Developing a Payable Hierarchy,Payable interfaceContains method getPaymentAmountIs implemented by the Invoice and Employee classesUML representation of interfacesInterfaces are di
30、stinguished from classes by placing the word “interface” in guillemets ( and ) above the interface nameThe relationship between a class and an interface is known as realizationA class “realizes” the methods of an interface,39,Fig. 10.10 | Payable interface hierarchy UML class diagram.,40,Outline,Pay
31、able.java,Declare interface Payable,Declare getPaymentAmount method which is implicitly public and abstract,41,Outline,Invoice.java(1 of 3),Class Invoice implements interface Payable,42,Outline,Invoice.java(2 of 3),43,Outline,Invoice.java(3 of 3),Declare getPaymentAmount to fulfill contract with int
32、erface Payable,44,10.7.3Creating Class Invoice,A class can implement as many interfaces as it needsUse a comma-separated list of interface names after keyword implementsExample: public class ClassName extends SuperclassName implements FirstInterface, SecondInterface, ,45,Outline,Employee.java(1 of 3
33、),Class Employee implements interface Payable,46,Outline,Employee.java(2 of 3),47,Outline,Employee.java(3 of 3),getPaymentAmount method is not implemented here,48,10.7.5Modifying Class SalariedEmployee for Use in the Payable Hierarchy,Objects of any subclasses of the class that implements the interf
34、ace can also be thought of as objects of the interfaceA reference to a subclass object can be assigned to an interface variable if the superclass implements that interface,49,Inheritance and interfaces are similar in their implementation of the “is-a” relationship. An object of a class that implemen
35、ts an interface may be thought of as an object of that interface type. An object of any subclasses of a class that implements an interface also can be thought of as an object of the interface type.,Software Engineering Observation 10.7,50,Outline,SalariedEmployee.java(1 of 2),Class SalariedEmployee
36、extends class Employee (which implements interface Payable),51,Outline,SalariedEmployee.java(2 of 2),Declare getPaymentAmount method instead of earnings method,52,Software Engineering Observation 10.8,The “is-a” relationship that exists between superclasses and subclasses, and between interfaces and
37、 the classes that implement them, holds when passing an object to a method. When a method parameter receives a variable of a superclass or interface type, the method processes the object received as an argument polymorphically.,53,Software Engineering Observation 10.9,Using a superclass reference, w
38、e can polymorphically invoke any method specified in the superclass declaration (and in class Object). Using an interface reference, we can polymorphically invoke any method specified in the interface declaration (and in class Object).,54,Outline,PayableInterfaceTest.java(1 of 2),Declare array of Pa
39、yable variables,Assigning references to Invoice objects to Payable variables,Assigning references to SalariedEmployee objects to Payable variables,55,Outline,PayableInterfaceTest.java(2 of 2),Call toString and getPaymentAmount methods polymorphically,56,Software Engineering Observation 10.10,All met
40、hods of class Object can be called by using a reference of an interface type. A reference refers to an object, and all objects inherit the methods of class Object.,57,10.7.7Declaring Constants with Interfaces,Interfaces can be used to declare constants used in many class declarationsThese constants
41、are implicitly public, static and finalUsing a static import declaration allows clients to use these constants with just their names,58,Software Engineering Observation 10.11,It is considered a better programming practice to create sets of constants as enumerations with keyword enum. See Section6.10
42、 for an introduction to enum and Section8.9 for additional enum details.,59,Fig. 10.16 | Common interfaces of the Java API.(Part 1 of 2),60,Fig. 10.16 | Common interfaces of the Java API. (Part 2 of 2),61,Fig. 10.17 | MyShape hierarchy.,62,Fig. 10.18 | MyShape hierarchy with MyBoundedShape.,63,Fig.
43、10.19 | Attributes and operations of classes BalanceInquiry, Withdrawal and Deposit.,64,10.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System,UML model for inheritanceThe generalization relationshipThe superclass is a generalization of the subclassesThe subcl
44、asses are specializations of the superclassTransaction superclassContains the methods and fields BalanceInquiry, Withdrawal and Deposit have in commonexecute methodaccountNumber field,65,Fig. 10. 20 | Class diagram modeling generalization of superclass Transaction and subclasses BalanceInquiry, With
45、drawal and Deposit. Note that abstract class names (e.g., Transaction) and method names (e.g., execute in class Transaction) appear in italics.,66,Fig. 10.21 | Class diagram of the ATM system (incorporating inheritance). Note that abstract class names (e.g., Transaction) appear in italics.,67,Softwa
46、re Engineering Observation 10.12,A complete class diagram shows all the associations among classes and all the attributes and operations for each class. When the number of class attributes, methods and associations is substantial (as in Fig.10.21 and Fig.10.22), a good practice that promotes readabi
47、lity is to divide this information between two class diagramsone focusing on associations and the other on attributes and methods.,68,10.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System (Cont.),Incorporating inheritance into the ATM system designIf class A
48、is a generalization of class B, then class B extends class AIf class A is an abstract class and class B is a subclass of class A, then class B must implement the abstract methods of class A if class B is to be a concrete class,69,Fig. 10.22 | Class diagram with attributes and operations (incorporati
49、ng inheritance). Note that abstract class names (e.g., Transaction) and method names (e.g., execute in class Transaction) appear in italic,70,Outline,Withdrawal.java,Subclass Withdrawal extends superclass Transaction,71,Outline,Withdrawal.java,Subclass Withdrawal extends superclass Transaction,72,Software Engineering Observation 10.13,