0% found this document useful (0 votes)
27 views44 pages

Lecture 6 - Polymorphism - 2

This document discusses polymorphism and abstraction in object-oriented programming. It begins with an overview of polymorphism, explaining that it allows performing the same action in different ways depending on the object type. It then provides examples of polymorphism using a zoo animal hierarchy with subclasses overriding a speak method. The document next discusses abstraction, explaining that abstract classes allow creating blueprints for subclasses to inherit from while defining common behavior. It provides examples using shapes to illustrate abstract classes and methods.

Uploaded by

Baaru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views44 pages

Lecture 6 - Polymorphism - 2

This document discusses polymorphism and abstraction in object-oriented programming. It begins with an overview of polymorphism, explaining that it allows performing the same action in different ways depending on the object type. It then provides examples of polymorphism using a zoo animal hierarchy with subclasses overriding a speak method. The document next discusses abstraction, explaining that abstract classes allow creating blueprints for subclasses to inherit from while defining common behavior. It provides examples using shapes to illustrate abstract classes and methods.

Uploaded by

Baaru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Polymorphism

(IT069IU)

Nguyen Trung Ky

📧 [email protected]

🌐 it.hcmiu.edu.vn/user/ntky
1
Previous lecture
- 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)
- Overloading
- Method Overloading
- Constructor Overloading
- Final Keyword
- Constant Variable
- Static Keyword
- Static Variable 2
- Static Method
Agenda’s today
- Polymorphism
- Method overriding and overloading in Inheritance
- Zoo Example
- Company Payroll Example
- Abstraction
- Abstract Class
- Abstract Method
- Why we need abstract class
- Examples:
- Zoo Example
- Company Payroll Example
- Interface
- Interface in real life examples
- Upgrade Company Payroll with Invoices Example
- Abstract vs Interface
3
Polymorphism
- Polymorphism literally means “many forms”.
- Polymorphism allows us to perform a single action in different ways. The same method is called in
different types of objects has different results. We can perform polymorphism in java by method
overloading and method overriding.
- 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.
a. Write all necessary classes.
b. Write a Test class which creates three objects: developer, designer and
manager and print out all information from these objects.
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

Output:

19
Why do we need abstract class

20
Abstraction

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

22
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. 23
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 or Cat.
- 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. 24
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.
25
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. 26
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.

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

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

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

30
Class Zoo with main method for Testing

Output:

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

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

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

34
Interface
Abstraction on steroid

40
Interface in real life (Piano)

41
Interface
- An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
- The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body.
- It is used to achieve abstraction and multiple inheritance in Java.

- Interface offers a capability requiring that unrelated classes implement a set


of common methods.
- Java Interface also represents the IS-A relationship.
- It cannot be instantiated just like the abstract class.

42
Interface Syntax
Declare an interface with the name
Relationship between class and
“InterfaceName” with two methods: interface:

A class extends another class, an


interface extends another interface,
but a class implements an interface.
43
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)?

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

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

47
Recap
- Polymorphism
- Method overriding and overloading in Inheritance
- Zoo Example
- Company Payroll Example
- Abstraction
- Abstract Class
- Abstract Method
- Why we need abstract class
- Examples:
- Zoo Example
- Company Payroll Example
- Interface
- Interface in real life examples
- Upgrade Company Payroll with Invoices Example
- Abstract vs Interface
57
Thank you for your listening!

“Motivation is what gets you started. Habit is


what keeps you going!”
Jim Ryun

58

You might also like