0% found this document useful (0 votes)
10 views

Lecture 7 - Polymorphism

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 7 - Polymorphism

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Polymorphism

(IT069IU)

Le Duy Tan, Ph.D.


📧 [email protected]

🌐 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

“DRY (Don’t Repeat Yourself)” 2


Agenda
- 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

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()

Dog Cat Duck

+speak() +speak() +speak()


- Each specific type of Animal responds to the method speak() in a unique way:
- a Dog speaks “Woof”
- a Duck speaks “Quack”
- a Cat speaks “Meow”
- The program issues the same message (i.e., speak) to each animal object, but
each object knows how to use its correct method of speaking.
- Relying on each object to know how to “do the right thing” in response to the
same method call is the key concept of polymorphism.
- With polymorphism, we can design and implement systems that are easily
extensible.
Animal
-name
-age

+speak()

Dog Cat Duck

+speak() +speak() +speak()


Let’s live code in Java!
Zoo Polymorphism

6
Superclass Animal

[Info] Just notice for the superclass Animal, we


declare the method speak() with a dummy
implementation for the body of this method.
(We can improve this later with abstract class)

7
Class Dog

[Info] The subclass Dog inherits


superclass Animal and override
the method speak() of the
superclass.

8
Class Cat

[Info] The subclass Cat inherits


superclass Animal and override
the method speak() of the
superclass.

9
Class Duck

[Info] The subclass Duck


inherits superclass Animal and
override the method speak() of
the superclass

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

[Info] This time, for the superclass Employee,


we implement the body of the method
earning() with something useful.

15
Class Developer

[Info] The subclass Developer inherits from the


superclass Employee and override the method
earning() of the superclass.

16
Class Designer

[Info] The subclass Designer inherits from the


superclass Employee and override the method
earning() of the superclass.

17
Class Manager

[Info] The subclass Manager inherits from the


superclass Employee and override the method
earning() of the superclass.

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:

The Draw method can be invoked for every


single shape in the system, and invoking each
shape produces a different result:
- Invoking the Draw method on a Circle object
draws a circle.
- Invoking the Draw method on a Rectangle
object draws a rectangle.
In essence, sending a message to an object
evokes a different response, depending on the
object. This is the essence of polymorphism. 22
Abstract Class
- Sometimes it’s useful to declare classes for which you never intend to create
objects.
- For Example, we created superclass like Animal or Employee but we would never
create any object from it but only use it to extends other subclasses like Dog, Cat or
Lecturer.
- Abstract Class allow you to create blueprints for concrete classes. An abstract
class provides a superclass from which other classes can inherit and thus share
a common design.
- Abstract Class can contains:
- At least one Abstract method: method without implementation (no body).
- Zero or more Concrete method: normal method with implementation.
- Abstract Class cannot be used to create objects because it is incomplete.
Abstract class are too general to create real objects—they specify only what is
common among subclasses.
- Subclasses must override abstract method (provide the implementations) to
become “concrete” classes, which you can create objects; otherwise, these
subclasses, too, will be abstract, which cannot create objects. 23
Abstract Class Syntax
- You make a class abstract by declaring it with keyword abstract, for example:

public abstract class Animal {...} // abstract class


- An abstract class normally contains one or more abstract methods

public abstract void eat(); // abstract method


- Abstract methods do not provide implementations. (Without a body)
- A class that contains abstract methods must be an abstract class even if
that class contains some concrete (non-abstract) methods.
- Each concrete subclass of an abstract superclass also must provide
concrete implementations of each of the superclass’s abstract methods.
- Constructors and static methods cannot be declared abstract.
- Can use abstract superclass names to invoke static methods declared in
those abstract superclasses.
24
Revisited Zoo with Abstract Class Animal
- Remember we would never create any object from superclass like Animal but
only use it to extends other subclasses like Dog, Cat and Duck.
- Also, we got to provide a dummy implementation for the method speak()
even though.

- 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.

Also, because method speak() is abstract, we don’t


need to provide any implementation and leave that
responsibility to other subclasses to complete that
abstract method.

26
Class Dog

[Info] The class Dog inherits the abstract superclass


Animal and it does complete the implementation of
the abstract method by overriding it so that’s why
class Dog is a concrete class (which can be used to
create objects of class Dog)

27
Class Duck

[Info] The class Duck inherits the abstract


superclass Animal and it does complete the
implementation of the abstract method by
overriding it so that’s why class Duck is a concrete
class (which can be used to create objects of class
Duck)

28
Class Cat

[Info] The class Cat inherits the abstract superclass


Animal and it does complete the implementation of
the abstract method by overriding it so that’s why
class Cat is a concrete class (which can be used to
create objects of class Cat)

29
Class Zoo with main method for Testing

Output
:

30
UML Diagram for Abstract Class and Abstract Method

class Animal appears in italics,


indicating that it’s an abstract
class.

Method speak() appears in italics,


indicating that it’s an 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

- Class Employee provides methods earnings and toString, in addition to the


get and set methods that manipulate Employee’s instance variables.
- An earnings method applies to all employees, but each earnings calculation
depends on the employee’s class.
- An abstract method—there is not enough information to determine what
amount earnings should return.
- Each subclass overrides earnings with an appropriate implementation.
- Iterate through the array of Employees and call method earnings for each
Employee subclass object.
- Method calls processed polymorphically.
- Declaring the earnings method abstract indicates that each concrete
subclass must provide an appropriate earnings implementation and that a
program will be able to use superclass Employee variables to invoke method
earnings polymorphically for any type of Employee.
33
Abstract Class Employee

[Info] the class Employee contains one abstract


method earning() that is why class Employee is an
abstract class.
Also, because method earning() is abstract, we
don’t need to provide any implementation and
leave that responsibility to other subclasses to
complete that abstract method.

34
Class Developer

[Info] The class Developer inherits the abstract


superclass Employee and it does complete the
implementation of the abstract method by
overriding it so that’s why class Developer is a
concrete class (which can be used to create objects
of class Developer)

35
Class Designer

[Info] The class Designer inherits the abstract


superclass Employee and it does complete the
implementation of the abstract method by
overriding it so that’s why class Designer is a
concrete class (which can be used to create objects
of class Designer)

36
Class Manager

[Info] The class Manager inherits the abstract


superclass Employee and it does complete the
implementation of the abstract method by
overriding it so that’s why class Manager is a
concrete class (which can be used to create objects
of 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:

Option 2: An abstract class can partly


implement some of the required methods of the
interface. Then let a concrete class to inherit
that abstract class and implement the rest of
the required methods.

public abstract class myAbstractClass implements InterfaceName{


Option 1: A class which implements an interface // one or more method of InterfaceName are not yet implemented
needs to implement all required methods of the // so the class must be abstract
interface to be a concrete class. }

public class myConcreteClass extends myAbstractClass{


public class myClass implements InterfaceName{
// implement the remaining method in InterfaceName
// implement all method of InterfaceName
} 47
}
Revisited the Company Payroll
Suppose that the company involved wishes to perform several accounting operations in a single accounts
payable application:
- Calculate the earnings that must be paid to each employee,
- Calculate the payment due on each of several invoices (i.e., bills for products purchased).
Though applied to unrelated things (employees and invoices), both want to do a kind of payment amount:
- For an employee, the payment refers to the employee’s earnings.
- For an invoice, the payment refers to the total cost of the goods listed on the invoice.
Can we calculate such different things as the payments due for employees and invoices in a single
application polymorphically? Does Java offer a capability requiring that unrelated classes implement a set of
common methods (e.g., a method that calculates a payment amount)?

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.

The UML expresses the relationship between a class


and an interface through a relationship known as realization.
A class is said to realize, or implement, the methods of an
interface. A class diagram models a realization as a dashed
arrow with a hollow arrowhead pointing from the
implementing class to the interface.

class Employee appears in italics, indicating that


it’s an abstract class.

Concrete class Developer,


Designer and Manager extends
Employee, inheriting its
superclass’s realization relationship
with interface Payable.
50
Interface Payable
- 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.

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.

[Info] The class Employee implements the


interface Payable but it does not make sense for
an employee to know how to get paid as there
are many types of employees (Employee is still
too general).
That is why we don’t implement the method
getPaymentAmound() yet so the class
Employee has to be abstract.

53
Class Developer

[Info] The class Developer inherits the abstract


superclass Employee and it does complete the
implementation of the method getPaymentAmount() by
overriding it so that’s why class Developer is a concrete
class (which can be used to create objects of class
Developer) 54
Class Designer

[Info] The class Designer inherits the abstract


superclass Employee and it does complete the
implementation of the method getPaymentAmount() by
overriding it so that’s why class Designer is a concrete
class (which can be used to create objects of class
Designer)
55
Class Manager

[Info] The class Manager inherits the abstract


superclass Employee and it does complete the
implementation of the method getPaymentAmount() by
overriding it so that’s why class Manager is a concrete
class (which can be used to create objects of class
Manager) 56
Class CompanyWithInterfaceTesting
Output:

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!

“Motivation is what gets you started. Habit is


what keeps you going!”
Jim Ryun

64

You might also like