Lecture 7 - Polymorphism
Lecture 7 - Polymorphism
International University
School of Computer Science and Engineering
Polymorphism
(IT069IU)
🌐 leduytanit.com 1
Previously,
- Inheritance:
- Definition and Examples
- Types of Inheritance
- UML Diagram
- Animal Inheritance Example
- Without Inheritance
- With Inheritance
- Method Overriding
- Constructors in Subclasses
- Keyword Super
- Method Overriding
- Keyword Super
- Access Modifier
- Protected
- Exercise for University Staff & Lecturer
3
Polymorphism
- Polymorphism literally means “many shapes”.
- The same method is called in different types of objects has different results.
- Enables you to “program in the general” rather than “program in the specific.”
- Polymorphism enables you to write programs that process objects of subclasses that share the
same superclass as if they’re all objects of the superclass; this can simplify programming.
Animal
-name
-age
+speak()
+speak()
6
Superclass Animal
7
Class Dog
8
Class Cat
9
Class Duck
10
Class ZooPolymorphism for Testing
Output:
11
Company Payroll Example
- A company has many employees. Each employee can be:
- Developer
- Designer
- Manager
- Every employee will has a fixed base salary but each type of employee can
have a different way to have bonus to be added for their salary:
- Developer:
- Base Salary + How many projects he did * The bonus for each project.
- Designer:
- Base Salary + 13th Salary Month if that person does a good job.
- Manager:
- Base Salary + How big is the team they manage * The bonus to manage each person.
12
UML Diagram for Company Payroll
13
Let’s live code in Java!
14
Superclass Employee
15
Class Developer
16
Class Designer
17
Class Manager
18
Class Company for Testing Three ways to assign superclass and subclass
references to variables of superclass and
subclass types:
1. Assigning a superclass reference to a
superclass variable is straightforward.
2. Assigning a subclass reference to a
subclass variable is straightforward.
3. Assigning a subclass reference to a
superclass variable is safe, because the
subclass object is an object of its superclass.
However, only the superclass variable can be
used to refer to superclass members.
Output:
19
Abstraction
20
Abstraction
- An abstract class is a class that contains one or more methods that do not
have any implementation provided.
- For example that you have an abstract class called Shape . It is abstract
because you cannot instantiate (create) it.
- If you ask someone to draw a shape, the first thing the person will most likely ask you is,
“What kind of shape?” Thus, the concept of a shape is abstract.
- However, if someone asks you to draw a circle, this is easier because a circle is a
concrete concept. You know what a circle looks like. You also know how to draw other
shapes, such as rectangles.
21
Abstraction in Shape
The class Shape does not provide any implementation for draw() ; basically there is no code, and this is
what makes the method abstract (providing any code would make the method concrete).
We want the subclasses to provide the implementation. Let’s look at the Circle and Rectangle classes:
- With abstract class, we can indicate that class should never be used to
create object directly. Also, the abstract class can provide abstract methods
for other classes to inherit it to provide specific implementation. 25
Abstract Class Zoo
[Info] The class Animal contains one abstract
method speak() that is why class Animal is an
abstract class.
26
Class Dog
27
Class Duck
28
Class Cat
29
Class Zoo with main method for Testing
Output
:
30
UML Diagram for Abstract Class and Abstract Method
31
Revisited Payroll System with Abstract Class
- Use an abstract method and polymorphism to perform payroll calculations
based on the type of inheritance by an employee.
- Abstract class Employee represents the general concept of an employee.
- Subclasses: Developer, Designer, Manager.
- Abstract superclass Employee declares the “protocol” —that is, the set of
methods that a program can invoke on all Employee objects.
- We use the term “protocol” here in a general sense to refer to the various
ways programs can communicate with objects of any Employee subclass.
- Each employee has a name and a base salary defined in abstract superclass
Employee.
32
Revisited Payroll System with Abstract Class
34
Class Developer
35
Class Designer
36
Class Manager
37
Class Company with main method for Testing
Output:
38
Polymorphism in Video Games
Example: Game Objects in a Video Game
▪ A video game manipulates objects of classes Zombie, SpaceShip and
FlyingMonster. Each inherits from an abstract class GameObject and overrides its
method draw().
▪ A screen manager class maintains a collection of references to objects of the
various classes and periodically sends each object the same message—draw()
Each object responds in a unique way:
● A Zombie object might draw itself in green skin and ugly appearance.
● A SpaceShip object might draw itself as a bright silver flying ship.
● A FlyingMonster object might draw itself as a cute flying pig monster across the screen.
▪ The same message (in this case, draw) sent to a variety of objects has “many
forms” of results.
39
Polymorphism & Abstraction in Video Games
▪ A screen manager class might use polymorphism to facilitate adding new classes to a
system with minimal modifications to the system’s code.
▪ To add new objects to our video game:
● Build a subclass that extends abstract class GameObject and provides its own draw method
implementation.
● When objects of that class appear in the GameObject collection, the screen manager code
invokes method draw, exactly as it does for every other object in the collection, regardless of its
type.
● So the new objects simply “plug right in” without any modification of the screen manager code
by the programmer.
40
Interface
Abstraction on steroid
41
Interface in real life (Car)
42
Interface in real life (Elevator)
43
Interface in real life (ATM)
44
Interface in real life (Piano)
45
Interface
- Interface offers a capability requiring that unrelated classes implement a set
of common methods.
- Standardizing Interactions: Interfaces define and standardize the ways in
which things such as people and systems can interact with one another
- Interfaces define a set of methods, attributes that any class that uses the
interface are required to provide.
- You can implement multiple interfaces at the same time. You can also
implement interfaces and inherit from a superclass at the same time.
46
Interface Syntax
- Declare an interface with the name “InterfaceName” with two methods:
48
Upgrade our Company Payroll with Interface
- To build an application that can determine payments for employees and invoices alike,
we first create interface Payable, which contains method getPaymentAmount() that
returns the amount that must be paid for an object of any class that implements the
interface.
- Method getPaymentAmount() is a general-purpose version of method earnings().
- Classes Invoice and Employee both represent things for which the company must be
able to calculate a payment amount. Both classes implement the Payable interface, so
a program can invoke method getPaymentAmount() on Invoice objects and Employee
objects alike.
49
UML Diagram The UML distinguishes an interface from other classes
by placing the word “interface” in guillemets (« and »)
above the interface name.
51
Class Invoice
[Info] After declaring interface Payable, we introduce class
Invoice, which implements, interface Payable.
52
Class Employee
[Info] We then modify class Employee such that
it also implements interface Payable.
53
Class Developer
Class CompanyWithInterfaceTesting
illustrates that interface Payable can be
used to process a set of Invoices and
Employees polymorphically in a single
application.
57
Abstract VS Interface vs Composition
58
Abstract VS Interface vs Composition?
- The obvious question is this: If an abstract
class can provide the same functionality
as an interface, why do Java bother to
provide an interface?
- If both abstract classes and interfaces
provide abstract methods, what is the real
difference between the two?
- As we saw before, an abstract class
provides both abstract and concrete
methods, whereas an interface provides
only abstract methods. Why is there such
a difference?
59
- In a nutshell, Java build objects in three ways: inheritance, interfaces, and
composition.
- This example illustrates when you should use which one. When do you choose an
abstract class? When do you choose an interface? When do you choose
composition?
- You should be familiar with the following concepts:
- Dog is a Mammal , so the relationship is inheritance.
- Dog implements Nameable , so the relationship is an interface.
- Dog has a Head , so the relationship is composition.
Although inheritance is a strict is-a relationship, an interface is not
quite. For example:
- A dog is a mammal.
- A toy is not a mammal.
Thus, a Toy class could not inherit from the Mammal class.
However, an interface applies for the various classes. For example:
- A dog is nameable.
- A teddy bear is nameable.
60
61
Interfaces vs. Abstract Classes
- Consider using abstract classes if any of these statements apply to your situation:
- You want to share code among several closely related classes.
- You want classes that inherit your abstract class have many common methods
or attributes.
- You want to declare final, non-final, static and non-static variables.
- You want to declare both abstract and non-abstract methods.
- You only need the subclass to only inherit (extends) from one class.
- Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface.
- You want to specify the behavior of a particular data type, but not concerned
about which class implements its behavior.
- You want to declare only static and final variables.
- You want to declare only abstract methods.
- You want to take advantage of multiple interface.
- Your problem makes the statement “A is capable of [doing this]”.
- “Clonable is capable of cloning an object”
- “Drawable is capable of drawing a shape”, 62
- “Payable is capable of returning a payment amount”.
Recap
- Polymorphism
- Method overriding in Inheritance
- Zoo Example
- Abstraction
- Abstract Class
- Abstract Method
- Examples:
- Zoo Example
- Company Payroll Example
- Interface
- Interface in real life examples
- Upgrade Company Payroll with Invoices Example
- Abstract vs Interface vs Composition
63
Thank you for your listening!
64