SlideShare a Scribd company logo
1 of 62
Download to read offline
Object-Oriented Programming: PolymorphismPolymorphism 
Chapter 10Chapter 10
2 
What You Will Learn 
What is polymorphism? 
How to declare and use virtual 
functions for abstract classes
3 
Problem with SubclassesProblem Subclasses 
Given the class hierarchy below 
Consider the existence of a draw function for each subclass 
Consider also an array of references to the superclass (which can also point to various objects of the subclasses) 
How do you specify which draw statement to be called when using the references 
Shape class hierarchy 
Circle 
Right Triangle 
Isosceles Triangle 
Triangle 
Square 
Rectangle 
Shape
4 
Introduction 
PolymorphismPolymorphism 
– Enables “programming in the general” 
– The same invocation can produce “many forms” of resultsforms” results 
InterfacesInterfaces 
– Implemented by classes to assign common functionality to possibly unrelated classes
5 
PolymorphismPolymorphism 
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 variablein variable 
The same method name and signature can cause different actions to occur, 
– depending on the type of object on which the method is invokedthe invoked
6 
PolymorphismPolymorphism 
 Polymorphism enables programmers to deal in generalities and 
– let the executionlet execution-time environment handle the specifics. 
 Programmers can command objects to behave in manners appropriate to those objects, 
– without knowing the types of the objects 
– (as long as the objects belong to the same inheritance hierarchy).
7 
Polymorphism Promotes ExtensibilityExtensibility 
 Software that invokes polymorphic behaviorbehavior 
– independent of the object types to which messages are sent. 
 New object types that can respond to existing method calls can be 
– incorporated into a system without requiring modification of the base system. 
–Only client code that instantiates new objects must be modified to accommodate new types.
8 
Demonstrating Polymorphic Behavior 
A superclass reference can be aimed at a subclass objecta object 
– a subclass object “is-a” superclass object 
– the type of the actual referenced objectobject, not the type of the referencereference, determines , which method is calledwhich called 
A subclass reference can be aimed at a superclass object only if the object is downcasteddowncasted 
View example, Figure 10.1
9 
PolymorphismPolymorphism 
 Promotes extensibilityPromotes extensibility 
 New objects types can respond to existing method callsexisting calls 
– Can be incorporated into a system without modifying base systemmodifying system 
 Only client code that instantiates the new objects must be modified 
– To accommodate new typesTo types
10 
Abstract Classes and MethodsAbstract Methods 
 Abstract classes 
– Are superclasses (called abstractabstract superclasses) 
– Cannot be instantiated 
– IncompleteIncomplete 
subclasses fill in "missing pieces" 
Concrete classesConcrete classes 
– Can be instantiatedCan instantiated 
– Implement every method they declareImplement declare 
– Provide specificsProvide specifics
11 
Abstract Classes and Methods 
 Purpose of an abstract classPurpose class 
– Declare common attributes … 
– Declare common behaviors of classes in a class hierarchyclass hierarchy 
 Contains one or more abstract methods 
– Subclasses must overrideSubclasses override 
 Instance variables, concrete methods of abstract classof class 
– subject to normal rules of inheritancesubject inheritance
12 
Abstract ClassesAbstract Classes 
Classes that are too general to create real objectscreate objects 
Used only as abstract superclasses for concrete subclasses and to declare reference variables 
Many inheritance hierarchies have abstract superclasses occupying the top few levelstop levels
13 
Keyword abstract 
Use to declare a class abstract 
Also use to declare a method abstractabstract 
Abstract classes normally contain one or more abstract methodsone methods 
All concrete subclasses must override all inherited abstract methods
14 
Abstract Classes and MethodsAbstract Methods 
Iterator class 
– Traverses all the objects in a collection, such as an arraycollection, array 
– Often used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchyfrom hierarchy
15 
Abstract ClassesAbstract Classes 
 Declares common attributes and behaviors of the various classes in a class hierarchy. 
 Typically contains one or more abstract methods 
– Subclasses must override if the subclasses are to be concrete. 
 Instance variables and concrete methods of an abstract class subject to the normal rules of inheritance.
16 
Beware! Compile Time ErrorsBeware! Errors 
 Attempting to instantiate an object of an abstract class 
 Failure to implement a superclass’s abstract methods in a subclass 
– unless the subclass is also declared abstract.
17 
Creating Abstract Superclass Employee 
abstract superclass Employee, Figure 10.4Figure 10.4 
– earnings is declared abstract 
No implementation can be given for earnings in the Employee abstract classclass 
– An array of Employee variables will store references to subclass objectsreferences objects 
earnings method calls from these variables will call the appropriate version of the earnings methodmethod
18 
Example Based on EmployeeExample Employee 
Abstract Class 
Concrete Classes 
Click on Classes to see source code
19 
Polymorphic interface for the Employee hierarchy classes.
20 
Note in Example HierarchyNote Hierarchy 
Dynamic bindingDynamic binding 
– Also known as late bindingAlso binding 
– Calls to overridden methods are resolved at execution time, based on the type of object referencedobject referenced 
 instanceof operatoroperator 
– Determines whether an object is an instance of a certain typeinstance type
21 
How Do They Do That? 
How does it work? 
– Access a derived object via base class pointerpointer 
– Invoke an abstract methodInvoke method 
– At run time the correct version of the method is usedmethod used 
 Design of the VDesign V-Table 
– Note description from C++
22 
Note in Example HierarchyNote Hierarchy 
 Downcasting 
– Convert a reference to a superclass to a reference to a subclassreference subclass 
– Allowed only if the object has an is-a relationship with the subclassrelationship subclass 
 getClass method 
– Inherited from Object 
– Returns an object of type Class 
 getName method of class Class 
– Returns the class’s nameReturns name
23 
Superclass And Subclass Assignment RulesAssignment Rules 
 Assigning a superclass reference to superclass variable straightforwardsuperclass straightforward 
 Subclass reference to subclass variable straightforwardstraightforward 
 Subclass reference to superclass variable safe 
– because of is-a relationshiprelationship 
– Referring to subclassReferring subclass-only members through superclass variables a compilation errorsuperclass error 
 Superclass reference to a subclass variable a compilation errorcompilation error 
– Downcasting can get around this errorDowncasting error
24 
final Methods and Classes 
final methods 
– Cannot be overridden in a subclassCannot subclass 
– private and static methods implicitly finalfinal 
– final methods are resolved at compile time, this is known as static bindingtime, binding 
Compilers can optimize by inlining the codeCompilers code 
final classes 
– Cannot be extended by a subclassCannot subclass 
– All methods in a final class implicitly final
25 
Why Use InterfacesWhy Interfaces 
 Java has single inheritance, only 
 This means that a child class inherits from only one parent class 
 Sometimes multiple inheritance would be convenient 
 InterfacesInterfaces give Java some of the advantages of multiple inheritance without incurring the disadvantages
26 
Why Use InterfacesWhy Interfaces 
 Provide capability for unrelated classes to implement a set of common methods 
 Define and standardize ways people and systems can interactand interact 
 Interface specifies what operations must be permittedmust permitted 
 Does not specify how performed
27 
What is an Interface? 
 An interface is a collection of constants and method declarations 
 An interface describes a set of methods that can be called on an object 
 The method declarations do not include an implementation 
– there is no method bodythere body
28 
What is an Interface? 
 A child class that extendsextends a parent class can also implement an interface to gain some additional behaviorto behavior 
Implementing an interface is a “promise” to include the specified method(s) 
 A method in an interface cannot be made privateprivate
29 
When A Class Definition ImplementsImplements An Interface: 
 It must implement each method in the interface 
 Each method must be publicpublic (even though the interface might not say so) 
 Constants from the interface can be used as if they had been defined in the class (They should not be reclass re-defined in the class)
30 
Declaring Constants with Interfaces 
Interfaces can be used to declare constants used in many class declarationsdeclarations 
– These constants are implicitly public, static and final 
– Using a static import declaration allows clients to use these constants with just their namestheir names
31 
Implementation vs. Interface InheritanceInheritance 
ImplementationImplementation InheritanceInheritance 
 Functionality high in the hierarchyhierarchy 
 Each new subclass inherits one or more methods declared in superclasssuperclass 
 Subclass uses superclass declarationssuperclass declarations 
Interface InheritanceInterface Inheritance 
 Functionality lower in hierarchyhierarchy 
 Superclass specifies one or more abstract methodsmethods 
 Must be declared for each class in hierarchyeach hierarchy 
 Overridden for subclass-specific implementations
32 
Creating and Using InterfacesCreating Interfaces 
 Declaration begins with interface keyword 
 Classes implement an interface (and its methods) 
 Contains public abstractabstract methods 
– Classes (that implementimplement the interface) must implement these methodsmust methods
33 
Creating and Using InterfacesCreating Interfaces 
Consider the possibility of having a class which manipulates mathematical functions 
 You want to send a functiona function as a parameterparameter 
– Note that C++ allows this directlyNote directly 
– Java does notJava not 
 This task can be accomplished with interfacesinterfaces
34 
Creating and Using InterfacesCreating Interfaces 
 Declare interface Function 
 Declare class MyFunction which implements Function 
 Note other functions which are subclass objects of MyFunction 
 View test program which passes Function subclass objects to function manipulation methodsmanipulation methods
35 
Case Study: A Payable Hierarchy 
 Payable interfaceinterface 
– Contains method getPaymentAmountgetPaymentAmount 
– Is implemented by the Invoice and Employee classesclasses 
Click to view the test program
36 
End of Chapter 10 Lecture
37 
Following slides are from previous edition. Links may not work.
38 
Source Code for Shape Superclass Hierarchy 
Shape superclass, Figure 10.6Figure 10.6 
– Note abstract method, getName 
 Point subclass, Figure 10.7 
– Note, extends Shape, override of , getName 
 Circle subclass, Figure 10.8 
– Note extends Point, override of , getArea, getName, and , toString 
 Cylinder subclass, Figure 10.9 
– Note extends Circle, override of getArea, getName, and , toString
39 
Source Code for Shape Superclass Hierarchy 
 Driver program to demonstrate, Figure 10.10Figure 10.10 
– Note array of superclass referencesNote references 
Output ofOutput of programprogram
40 
Polymorphic Payroll SystemPolymorphic System 
Class hierarchy for polymorphic payroll applicationClass application 
Employee 
SalariedEmployee 
HourlyEmployee 
CommissionEmployee 
BasePlusCommissionEmployee
41 
Polymorphic Payroll SystemPolymorphic System 
 Abstract superclass, Employee, Figure 10.12Figure 10.12 
– Note abstract class specification, abstract earnings method 
 Abstract subclass, SalariedEmployeeSalariedEmployee, Figure 10.13Figure 10.13 
– Note extends Employee, override of , earnings method 
 Look at other subclasses in text, pg 461 … 
– Note here also the override of earnings
42 
Polymorphic Payroll SystemPolymorphic System 
 View test program, Figure 10.17Figure 10.17 
– Note array of superclass references which are pointed at various subclass objectsare objects 
– Note generic calls of toString methodmethod 
– Note use of instantceof operatoroperator 
– Consider use of downcasting (line 37) 
– Note use of getClass().getName() method 
Gives access to the name of the classclass
43 
Polymorphic Payroll SystemPolymorphic System 
Output of the payroll testingpayroll testing programprogram 
 Note results of getClass().getName() calls
44 
Creating and Using InterfacesCreating Interfaces 
 View implementation of the interface Shape, Figure 10.19 Note the following: 
– Line 4Line 4 public class Point extends Object implements Shape { … 
– Declaration of additional methodsDeclaration methods 
– Declaration of abstract methods getArea, getVolume, and , getName
45 
Nested ClassesNested Classes 
Top-level classeslevel classes 
– Not declared inside a class or a methodNot method 
 Nested classesNested classes 
– Declared inside other classesDeclared classes 
– Inner classesInner classes 
Non-static nested classesstatic classes 
 Demonstrated in Figure 10.22 
– Run the programRun program 
– AudioAudio
46 
Mentioned In The Audio 
 Inheritance Hierarchy 
 Panes of a JFrame 
– BackgroundBackground 
– ContentContent 
– Glass 
Object 
Component 
Container 
Window 
Frame 
JFrame
47 
Mentioned In The Audio 
 Three things required when performing eventsperforming events 
1. Implement the interfaceImplement interface 
2. Register the event handlersRegister handlers 
3. Specifically implement the actionPerformedactionPerformed methods
48 
Nested ClassesNested Classes 
 An inner class is allowed to directly access its inner class's variables and methods 
When this used in an inner classused class 
– Refers to current innerRefers inner-class objectclass object 
 To access outer-class using this 
– Precede this with outerwith outer-class nameclass name
49 
Nested ClassesNested Classes 
Anonymous inner classAnonymous class 
– Declared inside a method of a classDeclared class 
– Has no nameHas name 
 Inner class declared inside a methodInner method 
– Can access outer class's membersCan members 
– Limited to local variables of method in which declaredwhich declared 
 Note use of anonymous inner class, Figure 10.23Figure 10.23
50 
Notes on Nested ClassesNotes Classes 
 Compiling class that contains nested classCompiling class 
– Results in separate .class file 
– OuterClassName$InnerClassName.classOuterClassName$class 
 Inner classes with names can be declared asInner as 
– public, protected, private or package accessor access
51 
Notes on Nested ClassesNotes Classes 
 Access outer class’s this referencereference 
OuterClassNameOuterClassName.this 
 Outer class is responsible for creating inner class objectsinner objects OuterClassName.InnerClassName innerRef = ref.new InnerClassName(); 
 Nested classes can be declared static 
– Object of outer class need not be createdObject created 
– Static nested class does not have access to outer class's nonto non-static membersstatic members
52 
Type-Wrapper Classes for Primitive Types 
 Each primitive type has oneEach one 
–Character, Byte, Integer, Boolean, etc., etc. 
Enable to represent primitive as ObjectObject 
– Primitive values can be processed polymorphically using wrapper classespolymorphically classes 
 Declared as final 
Many methods are declared static
53 
Invoking Superclass Methods from Subclass ObjectsSubclass Objects 
 Recall the point and circle hierarchyRecall hierarchy 
– Note : Assignment of superclass reference to superclass variablesuperclass variable 
– Assignment of subclass reference to subclass variablesubclass variable 
 No surprises … but the "isNo is-a" relationship makes possiblerelationship possible 
– Assignment of subclass reference to superclass variablesuperclass variable 
 See Figure 10.1
54 
Using Superclass References with SubclassSubclass-Type VariablesType Variables 
Suppose we have a superclass objectSuppose object Point3 point = new Point3 (30, 40); 
 Then a subclass referenceThen reference Circle4 circle; 
 It would be illegal to have the subclass reference aimed at the superclass object circle = point;
55 
Subclass Method Calls via SuperclassSuperclass-Type VariablesType Variables 
Consider aiming a subclass reference at a superclass objectreference object 
– If you use this to access a subclassIf subclass- only method it is illegalonly illegal 
 Note Figure 10.3 
– Lines 22 - 23
56 
Summary of Legal Assignments between SuperSuper- and Subclass Variablesand Variables 
 Assigning superclass reference to superclassAssigning superclass- type variable OKtype OK 
 Assigning subclass reference to subclassAssigning subclass- type variable OKtype OK 
 Assigning subclass object's reference to superclass typesuperclass type-variable, safevariable, safe 
– A circle "is a" pointA point 
– Only possible to invoke superclass methodsOnly methods 
 Do NOT assign superclass reference to subclasssubclass-type variabletype variable 
– You can cast the superclass reference to a subclass type (explicitly)
57 
Polymorphism ExamplesPolymorphism Examples 
Suppose designing video gameSuppose game 
 Superclass SpaceObject 
– Subclasses Martian, SpaceShip, LaserBeamMartian, LaserBeam 
– Contains method draw 
 To refresh screenTo screen 
– Send draw message to each objectmessage object 
– Same message has “many forms” of resultsSame results 
 Easy to add class Mercurian 
– Extends SpaceObject 
– Provides its own implementation of draw 
 Programmer does not need to change codeProgrammer code 
– Calls draw regardless of object’s typeregardless type 
– Mercurian objects “plug right in”
58 
PolymorphismPolymorphism 
Enables programmers to deal in generalitiesgeneralities 
– Let executionLet execution-time environment handle specificsspecifics 
 Able to command objects to behave in manners appropriate to those objectsmanners objects 
– Don't need to know type of the objectDon't object 
– Objects need only to belong to same inheritance hierarchyinheritance hierarchy
59 
Abstract Classes and MethodsAbstract Methods 
 Abstract classes not required, but reduce client code dependenciesreduce dependencies 
 To make a class abstractTo abstract 
– Declare with keyword abstract 
– Contain one or more abstract methodsabstract methods 
public abstract void draw(); 
– Abstract methodsAbstract methods 
No implementation, mustmust be overriddenbe overridden
60 
Inheriting Interface and Implementation 
Make abstract superclass Shape 
 Abstract method (must be implemented) 
– getName, print 
– Default implementation does not make senseDefault sense 
 Methods may be overriddenMethods overridden 
– getArea, getVolume 
 Default implementations return 0.0 
– If not overridden, uses superclass default implementation 
 Subclasses Point, Circle, Cylinder
61 
Circle 
Cylinder 
Point 
Shape 
Polymorphic Interface For The Shape Hierarchy Class 
0.0 
0.0 
abstract 
default Object implement 
0.0 
0.0 
"Point" 
[x,y] 
πr2 
0.0 
"Circle" 
center=[x,y]; radius=r 
2πr2 +2πrh 
πr2h 
"Cylinder" 
center=[x,y]; radius=r; height=h 
getArea 
toString 
getName 
getVolume 
Shape 
Point 
Circle 
Cylinder
62 
Creating and Using InterfacesCreating Interfaces 
 All the same "isAll is-a" relationships apply when an interface inheritance is usedwhen used 
 Objects of any class that extend the interface are also objects of the interface typeinterface type 
– Circle extends Point, thus it is, is-a Shape 
 Multiple interfaces are possibleMultiple possible 
–Comma-separated list used in declarationseparated declaration

More Related Content

What's hot

9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10Terry Yoast
 
Chapter 5 declaring classes & oop
Chapter 5 declaring classes  & oopChapter 5 declaring classes  & oop
Chapter 5 declaring classes & oopsshhzap
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAhmed Nobi
 

What's hot (20)

Classes2
Classes2Classes2
Classes2
 
7494605
74946057494605
7494605
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
C# interview questions
C# interview questionsC# interview questions
C# interview questions
 
C#
C#C#
C#
 
Chapter 5 declaring classes & oop
Chapter 5 declaring classes  & oopChapter 5 declaring classes  & oop
Chapter 5 declaring classes & oop
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Java presentation
Java presentationJava presentation
Java presentation
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Ppt chapter05
Ppt chapter05Ppt chapter05
Ppt chapter05
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Interfaces
InterfacesInterfaces
Interfaces
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
Ppt chapter03
Ppt chapter03Ppt chapter03
Ppt chapter03
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
14 interface
14  interface14  interface
14 interface
 

Viewers also liked

The Polymorphic Variable
The Polymorphic VariableThe Polymorphic Variable
The Polymorphic Variableadil raja
 
05 iec t1_s1_oo_ps_session_07
05 iec t1_s1_oo_ps_session_0705 iec t1_s1_oo_ps_session_07
05 iec t1_s1_oo_ps_session_07Niit Care
 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...
A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...
A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...adil raja
 
Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...
Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...
Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...LLGYeo
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scalab0ris_1
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 

Viewers also liked (14)

02.adt
02.adt02.adt
02.adt
 
The Polymorphic Variable
The Polymorphic VariableThe Polymorphic Variable
The Polymorphic Variable
 
05 iec t1_s1_oo_ps_session_07
05 iec t1_s1_oo_ps_session_0705 iec t1_s1_oo_ps_session_07
05 iec t1_s1_oo_ps_session_07
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...
A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...
A Methodology for Deriving VoIP Equipment Impairment Factors for a Mixed NB/W...
 
Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...
Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...
Object Oriented Programming Implementation of Scalar, Vector, and Tensor Vari...
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scala
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
polymorphism
polymorphism polymorphism
polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similar to L5

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview QestionsArun Vasanth
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 eehomeworkping9
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core ParcticalGaurav Mehta
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extraNurhanna Aziz
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)It Academy
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesHabtamu Wolde
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersMadhavendra Dutt
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.pptAshwathGupta
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegantalenttransform
 

Similar to L5 (20)

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
JavaHTP6e_10.ppt
JavaHTP6e_10.pptJavaHTP6e_10.ppt
JavaHTP6e_10.ppt
 
Core java questions
Core java questionsCore java questions
Core java questions
 
C# interview
C# interviewC# interview
C# interview
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
L05 Frameworks
L05 FrameworksL05 Frameworks
L05 Frameworks
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Java session2
Java session2Java session2
Java session2
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and Interfaces
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Unit 3
Unit 3Unit 3
Unit 3
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 

More from lksoo

More from lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L7
L7L7
L7
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

L5

  • 2. 2 What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes
  • 3. 3 Problem with SubclassesProblem Subclasses Given the class hierarchy below Consider the existence of a draw function for each subclass Consider also an array of references to the superclass (which can also point to various objects of the subclasses) How do you specify which draw statement to be called when using the references Shape class hierarchy Circle Right Triangle Isosceles Triangle Triangle Square Rectangle Shape
  • 4. 4 Introduction PolymorphismPolymorphism – Enables “programming in the general” – The same invocation can produce “many forms” of resultsforms” results InterfacesInterfaces – Implemented by classes to assign common functionality to possibly unrelated classes
  • 5. 5 PolymorphismPolymorphism 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 variablein variable The same method name and signature can cause different actions to occur, – depending on the type of object on which the method is invokedthe invoked
  • 6. 6 PolymorphismPolymorphism  Polymorphism enables programmers to deal in generalities and – let the executionlet execution-time environment handle the specifics.  Programmers can command objects to behave in manners appropriate to those objects, – without knowing the types of the objects – (as long as the objects belong to the same inheritance hierarchy).
  • 7. 7 Polymorphism Promotes ExtensibilityExtensibility  Software that invokes polymorphic behaviorbehavior – independent of the object types to which messages are sent.  New object types that can respond to existing method calls can be – incorporated into a system without requiring modification of the base system. –Only client code that instantiates new objects must be modified to accommodate new types.
  • 8. 8 Demonstrating Polymorphic Behavior A superclass reference can be aimed at a subclass objecta object – a subclass object “is-a” superclass object – the type of the actual referenced objectobject, not the type of the referencereference, determines , which method is calledwhich called A subclass reference can be aimed at a superclass object only if the object is downcasteddowncasted View example, Figure 10.1
  • 9. 9 PolymorphismPolymorphism  Promotes extensibilityPromotes extensibility  New objects types can respond to existing method callsexisting calls – Can be incorporated into a system without modifying base systemmodifying system  Only client code that instantiates the new objects must be modified – To accommodate new typesTo types
  • 10. 10 Abstract Classes and MethodsAbstract Methods  Abstract classes – Are superclasses (called abstractabstract superclasses) – Cannot be instantiated – IncompleteIncomplete subclasses fill in "missing pieces" Concrete classesConcrete classes – Can be instantiatedCan instantiated – Implement every method they declareImplement declare – Provide specificsProvide specifics
  • 11. 11 Abstract Classes and Methods  Purpose of an abstract classPurpose class – Declare common attributes … – Declare common behaviors of classes in a class hierarchyclass hierarchy  Contains one or more abstract methods – Subclasses must overrideSubclasses override  Instance variables, concrete methods of abstract classof class – subject to normal rules of inheritancesubject inheritance
  • 12. 12 Abstract ClassesAbstract Classes Classes that are too general to create real objectscreate objects Used only as abstract superclasses for concrete subclasses and to declare reference variables Many inheritance hierarchies have abstract superclasses occupying the top few levelstop levels
  • 13. 13 Keyword abstract Use to declare a class abstract Also use to declare a method abstractabstract Abstract classes normally contain one or more abstract methodsone methods All concrete subclasses must override all inherited abstract methods
  • 14. 14 Abstract Classes and MethodsAbstract Methods Iterator class – Traverses all the objects in a collection, such as an arraycollection, array – Often used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchyfrom hierarchy
  • 15. 15 Abstract ClassesAbstract Classes  Declares common attributes and behaviors of the various classes in a class hierarchy.  Typically contains one or more abstract methods – Subclasses must override if the subclasses are to be concrete.  Instance variables and concrete methods of an abstract class subject to the normal rules of inheritance.
  • 16. 16 Beware! Compile Time ErrorsBeware! Errors  Attempting to instantiate an object of an abstract class  Failure to implement a superclass’s abstract methods in a subclass – unless the subclass is also declared abstract.
  • 17. 17 Creating Abstract Superclass Employee abstract superclass Employee, Figure 10.4Figure 10.4 – earnings is declared abstract No implementation can be given for earnings in the Employee abstract classclass – An array of Employee variables will store references to subclass objectsreferences objects earnings method calls from these variables will call the appropriate version of the earnings methodmethod
  • 18. 18 Example Based on EmployeeExample Employee Abstract Class Concrete Classes Click on Classes to see source code
  • 19. 19 Polymorphic interface for the Employee hierarchy classes.
  • 20. 20 Note in Example HierarchyNote Hierarchy Dynamic bindingDynamic binding – Also known as late bindingAlso binding – Calls to overridden methods are resolved at execution time, based on the type of object referencedobject referenced  instanceof operatoroperator – Determines whether an object is an instance of a certain typeinstance type
  • 21. 21 How Do They Do That? How does it work? – Access a derived object via base class pointerpointer – Invoke an abstract methodInvoke method – At run time the correct version of the method is usedmethod used  Design of the VDesign V-Table – Note description from C++
  • 22. 22 Note in Example HierarchyNote Hierarchy  Downcasting – Convert a reference to a superclass to a reference to a subclassreference subclass – Allowed only if the object has an is-a relationship with the subclassrelationship subclass  getClass method – Inherited from Object – Returns an object of type Class  getName method of class Class – Returns the class’s nameReturns name
  • 23. 23 Superclass And Subclass Assignment RulesAssignment Rules  Assigning a superclass reference to superclass variable straightforwardsuperclass straightforward  Subclass reference to subclass variable straightforwardstraightforward  Subclass reference to superclass variable safe – because of is-a relationshiprelationship – Referring to subclassReferring subclass-only members through superclass variables a compilation errorsuperclass error  Superclass reference to a subclass variable a compilation errorcompilation error – Downcasting can get around this errorDowncasting error
  • 24. 24 final Methods and Classes final methods – Cannot be overridden in a subclassCannot subclass – private and static methods implicitly finalfinal – final methods are resolved at compile time, this is known as static bindingtime, binding Compilers can optimize by inlining the codeCompilers code final classes – Cannot be extended by a subclassCannot subclass – All methods in a final class implicitly final
  • 25. 25 Why Use InterfacesWhy Interfaces  Java has single inheritance, only  This means that a child class inherits from only one parent class  Sometimes multiple inheritance would be convenient  InterfacesInterfaces give Java some of the advantages of multiple inheritance without incurring the disadvantages
  • 26. 26 Why Use InterfacesWhy Interfaces  Provide capability for unrelated classes to implement a set of common methods  Define and standardize ways people and systems can interactand interact  Interface specifies what operations must be permittedmust permitted  Does not specify how performed
  • 27. 27 What is an Interface?  An interface is a collection of constants and method declarations  An interface describes a set of methods that can be called on an object  The method declarations do not include an implementation – there is no method bodythere body
  • 28. 28 What is an Interface?  A child class that extendsextends a parent class can also implement an interface to gain some additional behaviorto behavior Implementing an interface is a “promise” to include the specified method(s)  A method in an interface cannot be made privateprivate
  • 29. 29 When A Class Definition ImplementsImplements An Interface:  It must implement each method in the interface  Each method must be publicpublic (even though the interface might not say so)  Constants from the interface can be used as if they had been defined in the class (They should not be reclass re-defined in the class)
  • 30. 30 Declaring Constants with Interfaces Interfaces can be used to declare constants used in many class declarationsdeclarations – These constants are implicitly public, static and final – Using a static import declaration allows clients to use these constants with just their namestheir names
  • 31. 31 Implementation vs. Interface InheritanceInheritance ImplementationImplementation InheritanceInheritance  Functionality high in the hierarchyhierarchy  Each new subclass inherits one or more methods declared in superclasssuperclass  Subclass uses superclass declarationssuperclass declarations Interface InheritanceInterface Inheritance  Functionality lower in hierarchyhierarchy  Superclass specifies one or more abstract methodsmethods  Must be declared for each class in hierarchyeach hierarchy  Overridden for subclass-specific implementations
  • 32. 32 Creating and Using InterfacesCreating Interfaces  Declaration begins with interface keyword  Classes implement an interface (and its methods)  Contains public abstractabstract methods – Classes (that implementimplement the interface) must implement these methodsmust methods
  • 33. 33 Creating and Using InterfacesCreating Interfaces Consider the possibility of having a class which manipulates mathematical functions  You want to send a functiona function as a parameterparameter – Note that C++ allows this directlyNote directly – Java does notJava not  This task can be accomplished with interfacesinterfaces
  • 34. 34 Creating and Using InterfacesCreating Interfaces  Declare interface Function  Declare class MyFunction which implements Function  Note other functions which are subclass objects of MyFunction  View test program which passes Function subclass objects to function manipulation methodsmanipulation methods
  • 35. 35 Case Study: A Payable Hierarchy  Payable interfaceinterface – Contains method getPaymentAmountgetPaymentAmount – Is implemented by the Invoice and Employee classesclasses Click to view the test program
  • 36. 36 End of Chapter 10 Lecture
  • 37. 37 Following slides are from previous edition. Links may not work.
  • 38. 38 Source Code for Shape Superclass Hierarchy Shape superclass, Figure 10.6Figure 10.6 – Note abstract method, getName  Point subclass, Figure 10.7 – Note, extends Shape, override of , getName  Circle subclass, Figure 10.8 – Note extends Point, override of , getArea, getName, and , toString  Cylinder subclass, Figure 10.9 – Note extends Circle, override of getArea, getName, and , toString
  • 39. 39 Source Code for Shape Superclass Hierarchy  Driver program to demonstrate, Figure 10.10Figure 10.10 – Note array of superclass referencesNote references Output ofOutput of programprogram
  • 40. 40 Polymorphic Payroll SystemPolymorphic System Class hierarchy for polymorphic payroll applicationClass application Employee SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee
  • 41. 41 Polymorphic Payroll SystemPolymorphic System  Abstract superclass, Employee, Figure 10.12Figure 10.12 – Note abstract class specification, abstract earnings method  Abstract subclass, SalariedEmployeeSalariedEmployee, Figure 10.13Figure 10.13 – Note extends Employee, override of , earnings method  Look at other subclasses in text, pg 461 … – Note here also the override of earnings
  • 42. 42 Polymorphic Payroll SystemPolymorphic System  View test program, Figure 10.17Figure 10.17 – Note array of superclass references which are pointed at various subclass objectsare objects – Note generic calls of toString methodmethod – Note use of instantceof operatoroperator – Consider use of downcasting (line 37) – Note use of getClass().getName() method Gives access to the name of the classclass
  • 43. 43 Polymorphic Payroll SystemPolymorphic System Output of the payroll testingpayroll testing programprogram  Note results of getClass().getName() calls
  • 44. 44 Creating and Using InterfacesCreating Interfaces  View implementation of the interface Shape, Figure 10.19 Note the following: – Line 4Line 4 public class Point extends Object implements Shape { … – Declaration of additional methodsDeclaration methods – Declaration of abstract methods getArea, getVolume, and , getName
  • 45. 45 Nested ClassesNested Classes Top-level classeslevel classes – Not declared inside a class or a methodNot method  Nested classesNested classes – Declared inside other classesDeclared classes – Inner classesInner classes Non-static nested classesstatic classes  Demonstrated in Figure 10.22 – Run the programRun program – AudioAudio
  • 46. 46 Mentioned In The Audio  Inheritance Hierarchy  Panes of a JFrame – BackgroundBackground – ContentContent – Glass Object Component Container Window Frame JFrame
  • 47. 47 Mentioned In The Audio  Three things required when performing eventsperforming events 1. Implement the interfaceImplement interface 2. Register the event handlersRegister handlers 3. Specifically implement the actionPerformedactionPerformed methods
  • 48. 48 Nested ClassesNested Classes  An inner class is allowed to directly access its inner class's variables and methods When this used in an inner classused class – Refers to current innerRefers inner-class objectclass object  To access outer-class using this – Precede this with outerwith outer-class nameclass name
  • 49. 49 Nested ClassesNested Classes Anonymous inner classAnonymous class – Declared inside a method of a classDeclared class – Has no nameHas name  Inner class declared inside a methodInner method – Can access outer class's membersCan members – Limited to local variables of method in which declaredwhich declared  Note use of anonymous inner class, Figure 10.23Figure 10.23
  • 50. 50 Notes on Nested ClassesNotes Classes  Compiling class that contains nested classCompiling class – Results in separate .class file – OuterClassName$InnerClassName.classOuterClassName$class  Inner classes with names can be declared asInner as – public, protected, private or package accessor access
  • 51. 51 Notes on Nested ClassesNotes Classes  Access outer class’s this referencereference OuterClassNameOuterClassName.this  Outer class is responsible for creating inner class objectsinner objects OuterClassName.InnerClassName innerRef = ref.new InnerClassName();  Nested classes can be declared static – Object of outer class need not be createdObject created – Static nested class does not have access to outer class's nonto non-static membersstatic members
  • 52. 52 Type-Wrapper Classes for Primitive Types  Each primitive type has oneEach one –Character, Byte, Integer, Boolean, etc., etc. Enable to represent primitive as ObjectObject – Primitive values can be processed polymorphically using wrapper classespolymorphically classes  Declared as final Many methods are declared static
  • 53. 53 Invoking Superclass Methods from Subclass ObjectsSubclass Objects  Recall the point and circle hierarchyRecall hierarchy – Note : Assignment of superclass reference to superclass variablesuperclass variable – Assignment of subclass reference to subclass variablesubclass variable  No surprises … but the "isNo is-a" relationship makes possiblerelationship possible – Assignment of subclass reference to superclass variablesuperclass variable  See Figure 10.1
  • 54. 54 Using Superclass References with SubclassSubclass-Type VariablesType Variables Suppose we have a superclass objectSuppose object Point3 point = new Point3 (30, 40);  Then a subclass referenceThen reference Circle4 circle;  It would be illegal to have the subclass reference aimed at the superclass object circle = point;
  • 55. 55 Subclass Method Calls via SuperclassSuperclass-Type VariablesType Variables Consider aiming a subclass reference at a superclass objectreference object – If you use this to access a subclassIf subclass- only method it is illegalonly illegal  Note Figure 10.3 – Lines 22 - 23
  • 56. 56 Summary of Legal Assignments between SuperSuper- and Subclass Variablesand Variables  Assigning superclass reference to superclassAssigning superclass- type variable OKtype OK  Assigning subclass reference to subclassAssigning subclass- type variable OKtype OK  Assigning subclass object's reference to superclass typesuperclass type-variable, safevariable, safe – A circle "is a" pointA point – Only possible to invoke superclass methodsOnly methods  Do NOT assign superclass reference to subclasssubclass-type variabletype variable – You can cast the superclass reference to a subclass type (explicitly)
  • 57. 57 Polymorphism ExamplesPolymorphism Examples Suppose designing video gameSuppose game  Superclass SpaceObject – Subclasses Martian, SpaceShip, LaserBeamMartian, LaserBeam – Contains method draw  To refresh screenTo screen – Send draw message to each objectmessage object – Same message has “many forms” of resultsSame results  Easy to add class Mercurian – Extends SpaceObject – Provides its own implementation of draw  Programmer does not need to change codeProgrammer code – Calls draw regardless of object’s typeregardless type – Mercurian objects “plug right in”
  • 58. 58 PolymorphismPolymorphism Enables programmers to deal in generalitiesgeneralities – Let executionLet execution-time environment handle specificsspecifics  Able to command objects to behave in manners appropriate to those objectsmanners objects – Don't need to know type of the objectDon't object – Objects need only to belong to same inheritance hierarchyinheritance hierarchy
  • 59. 59 Abstract Classes and MethodsAbstract Methods  Abstract classes not required, but reduce client code dependenciesreduce dependencies  To make a class abstractTo abstract – Declare with keyword abstract – Contain one or more abstract methodsabstract methods public abstract void draw(); – Abstract methodsAbstract methods No implementation, mustmust be overriddenbe overridden
  • 60. 60 Inheriting Interface and Implementation Make abstract superclass Shape  Abstract method (must be implemented) – getName, print – Default implementation does not make senseDefault sense  Methods may be overriddenMethods overridden – getArea, getVolume  Default implementations return 0.0 – If not overridden, uses superclass default implementation  Subclasses Point, Circle, Cylinder
  • 61. 61 Circle Cylinder Point Shape Polymorphic Interface For The Shape Hierarchy Class 0.0 0.0 abstract default Object implement 0.0 0.0 "Point" [x,y] πr2 0.0 "Circle" center=[x,y]; radius=r 2πr2 +2πrh πr2h "Cylinder" center=[x,y]; radius=r; height=h getArea toString getName getVolume Shape Point Circle Cylinder
  • 62. 62 Creating and Using InterfacesCreating Interfaces  All the same "isAll is-a" relationships apply when an interface inheritance is usedwhen used  Objects of any class that extend the interface are also objects of the interface typeinterface type – Circle extends Point, thus it is, is-a Shape  Multiple interfaces are possibleMultiple possible –Comma-separated list used in declarationseparated declaration