Presentation on theme: "Object Oriented Programming using Java - Polymorphism"— Presentation transcript:
1 Object Oriented Programming using Java - Polymorphism Department of Computer and Information Science, School of Science, IUPUIObject Oriented Programming using Java - PolymorphismDale Roberts, LecturerComputer Science, IUPUI
2 10.1 Introduction Polymorphism Interfaces Enables “programming in the general”The same invocation can produce “many forms” of resultsInterfacesImplemented by classes to assign common functionality to possibly unrelated classes
3 10.2 Polymorphism Examples When a program invokes a method through a superclass variable, the correct subclass version of the method is called, based on the type of the reference 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 system’s code
4 10.3 Demonstrating Polymorphic Behavior 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 reference can be aimed at a superclass object only if the object is downcasted
5 OutlinePolymorphismTest.java(1 of 2)Typical reference assignments
6 Outline PolymorphismTest .java Assign a reference to a basePlusCommissionEmployee object to a CommissionEmployee3 variableOutlinePolymorphismTest.java(2 of 2)Polymorphically call basePlusCommissionEmployee’s toString method
7 Abstract Classes and Methods Classes 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 the 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.4 Abstract Classes and Methods (Cont.) Iterator classTraverses all 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 “interface” or “implementation” from a superclass. Hierarchies designed for implementation inheritance tend to have their functionality high in the hierarchy—each new subclass inherits one or more methods that were implemented in a superclass, and the subclass uses the superclass implementations. (cont…)
11 Software Engineering Observation 10.4 Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchy—a superclass specifies one or more abstract methods that must be declared for each concrete class in the hierarchy, and the individual subclasses override these methods to provide subclass-specific implementations.
12 Creating Abstract Superclass Employee earnings is declared abstractNo implementation can be given for earnings in the Employee abstract classAn array of Employee variables will store references to subclass objectsearnings 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 Declare abstract class Employee Employee.java (1 of 3)Attributes common to all employees
16 Outline Employee.java abstract method earnings has no implementation (3 of 3)abstract method earnings has no implementation
17 Outline Class SalariedEmployee extends class Employee SalariedEmployee .java(1 of 2)Call superclass constructorCall setWeeklySalary methodValidate and set weekly salary value
18 Outline SalariedEmployee .java (2 of 2) Override earnings method so SalariedEmployee can be concreteOverride toString methodCall superclass’s version of toString
19 Outline Class HourlyEmployee extends class Employee HourlyEmployee .java(1 of 2)Call superclass constructorValidate and set hourly wage value
20 Outline HourlyEmployee .java Validate and set hours worked value (2 of 2)Validate and set hours worked valueOverride earnings method so HourlyEmployee can be concreteOverride toString methodCall superclass’s toString method
21 Outline CommissionEmployee.java Class CommissionEmployee extends class EmployeeCommissionEmployee.java(1 of 3)Call superclass constructorValidate and set commission rate value
22 Outline CommissionEmployee.java Validate and set the gross sales value (2 of 3)Validate and set the gross sales value
23 Outline CommissionEmployee.java Override earnings method so CommissionEmployee can be concreteCommissionEmployee.java(3 of 3)Override toString methodCall superclass’s toString method
24 Outline BasePlusCommissionEmployee.java Class BasePlusCommissionEmployee extends class CommissionEmployeeOutlineBasePlusCommissionEmployee.java(1 of 2)Call superclass constructorValidate and set base salary value
27 Outline PayrollSystemTest .java (2 of 5)Assigning subclass objects to supercalss variablesImplicitly and polymorphically call toString
28 Outline PayrollSystemTest .java If the currentEmployee variable points to a BasePlusCommissionEmployee objectPayrollSystemTest.java(3 of 5)Downcast currentEmployee to a BasePlusCommissionEmployee referenceGive BasePlusCommissionEmployees a 10% base salary bonusPolymorphically call earnings methodCall getClass and getName methods to display each Employee subclass object’s class name
30 Outline PayrollSystemTest .java Same results as when the employees were processed individuallyPayrollSystemTest.java(5 of 5)Base salary is increased by 10%Each employee’s type is displayed
31 10.5.7 Summary of the Allowed Assignments Between Superclass and Subclass Variables Superclass and subclass assignment 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 superclass variables is a compilation errorAssigning a superclass reference to a subclass variable is a compilation errorDowncasting can get around this error
32 10.6 final Methods and Classes Cannot be overridden in a subclassprivate and static methods are implicitly finalfinal methods are 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.1The compiler can decide to inline a final method call and will do so for small, simple 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 Software Engineering Observation 10.6 In the Java API, the vast majority of classes are not declared final. This enables inheritance and polymorphism—the fundamental capabilities of object-oriented programming. However, in some cases, it is important to declare classes final—typically for security reasons.
35 10.7 Case Study: Creating and Using Interfaces Keyword interfaceContains only constants and abstract methodsAll 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 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 interface’s methods without keywords 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 class that implements the interface results in a syntax error indicating that the class must be declared abstract.
38 10.7.1 Developing a Payable Hierarchy Payable interfaceContains method getPaymentAmountIs implemented by the Invoice and Employee classesUML representation of interfacesInterfaces are distinguished 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 Payable.java Declare interface Payable Declare getPaymentAmount method which is implicitly public and abstract
41 Outline Invoice.java Class Invoice implements interface Payable (1 of 3)
43 OutlineInvoice.java(3 of 3)Declare getPaymentAmount to fulfill contract with interface Payable
44 10.7.3 Creating 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 Class Employee implements interface Payable (1 of 3)
47 Outline Employee.java getPaymentAmount method is not implemented here (3 of 3)getPaymentAmount method is not implemented here
48 10.7.5 Modifying Class SalariedEmployee for Use in the Payable Hierarchy Objects of any subclasses of the class that implements the interface 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 Software Engineering Observation 10.7 Inheritance and interfaces are similar in their implementation of the “is-a” relationship. An object of a class that implements 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.
50 Outline SalariedEmployee .java Class SalariedEmployee extends class Employee (which implements interface Payable)SalariedEmployee.java(1 of 2)
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 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, we 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 PayableInterface Test.java Declare array of Payable variables Assigning references to Invoice objects to Payable variablesAssigning references to SalariedEmployee objects to Payable variables
55 Outline PayableInterface Test.java (2 of 2)Call toString and getPaymentAmount methods polymorphically
56 Software Engineering Observation 10.10 All methods 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.7 Declaring Constants with Interfaces Interfaces can be used to declare constants used in many class declarationsThese constants 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 Section 6.10 for an introduction to enum and Section 8.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)
62 Fig. 10.18 | MyShape hierarchy with MyBoundedShape.
63 Fig. 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 subclasses are specializations of the superclassTransaction superclassContains the methods and fields BalanceInquiry, Withdrawal and Deposit have in commonexecute methodaccountNumber field
65 Fig | Class diagram modeling generalization of superclass Transaction and subclasses BalanceInquiry, Withdrawal and Deposit. Note that abstract class names (e.g., Transaction) and method names (e.g., execute in class Transaction) appear in italics.
66 Fig | Class diagram of the ATM system (incorporating inheritance). Note that abstract class names (e.g., Transaction) appear in italics.
67 Software 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 readability is to divide this information between two class diagrams—one 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 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 | Class diagram with attributes and operations (incorporating inheritance). Note that abstract class names (e.g., Transaction) and method names (e.g., execute in class Transaction) appear in italic
72 Software Engineering Observation 10.13 Several UML modeling tools convert UML-based designs into Java code and can speed the implementation process considerably. For more information on these tools, refer to the Internet and Web Resources listed at the end of Section 2.9.
73 Outline Declare abstract superclass Transaction Transaction.java (1 of 2)
74 OutlineTransaction.java(2 of 2)Declare abstract method execute