Chapter 6 - Poplymorphism

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

CHAPTER 5

Polymorphism

By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Science, UiTM
Perlis
Objectives
• By the end of this chapter, students should be able to:

Define polymorphism and explore its benefits.

Use inheritance to create polymorphic references.

Be able to create concrete sub classes and methods.

Be able to create the array of super classes.

Be able to write an application program to implement polymorphism


concepts. 2
Introduction
(Why Polymorphism?)
• Example:
There are two different classes, A and B, A related to B because B inherits
A. Both A and B has a same method name (calcCost()) but with different
statements in their body.
public class A public class B extends A
{ {
protected double cost; protected double cost;
public double calcCost() public double calcCost()
{ {
return 0.0; cost = 360.00 * 0.75;
} return cost;
} }
}
This is what you have done/learned
in previous chapter (Inheritance)

POLYMORPHISM 3
Introduction
• Polymorphism refers to the ability to associate many meanings
to one method name by a special mechanism known as late
binding (dynamic binding).

• Binding refers to the process of associating a method definition


with a method invocation.
1. If method invocation is associated with the method invocation when the
code is compiled, that is called early binding.
2. If the method invocation is associated with the method invocation when
the method is invoked (at run time), that is called late binding (dynamic
binding).

4
Introduction
• Polymorphism refers to many forms. It comes from Greek word "poly"
(means many) and "morphos" (means form).

• There are many forms of the same methods to describe different actions.

• Polymorphism is the ability for two separate, yet related classes to


receive the same message but act on it in their own way – same method
name but with different ways of implementation.

• With polymorphism, it becomes possible to design and implement a


system that is more easily extensible. The program can be written to
process objects of types that might not exist when the program is under
development.
5
Introduction
• Inheritance allows you to define a base class and
derive classes from the base class.

• Polymorphism allows you to make changes in the


method definition for the derived classes and have
those changes apply to the methods written in the
base class.

• Advantage: Makes possible smooth and easy


extension and modification of a program. 6
Constructing Polymorphism
(Abstract Class)
• Example:
public abstract class AbstractClassExample
{
public abstract double calculateArea();
public abstract double calculatePerimeter();
public abstract String toString();
}

7
Constructing Polymorphism
(Abstract Class)
• Abstract class – is the class that has the common attributes and
methods of several classes.

• There are two types of methods in this class:

Abstract Method. The methods within this class


have no implementation – it has only the heading
with no body. [methods’ prototypes (method
declaration)].

Normal Method. Ex: Constructor, Mutator, Accessor,


Printer, Processor

8
Constructing Polymorphism
(Abstract Class)
• All other classes (concrete class) will extend from this
abstract class and provide the implementation of the
methods’ body (methods’ definition).

9
Constructing Polymorphism
(Abstract Method)
• An abstract method is a method with only signature (i.e., the
method name, the list of arguments and the return type) without
implementation (i.e., the method’s body).

• You use the keyword abstract to declare an abstract method


and ends with a semicolon.
• Example: These abstract methods cannot be invoked
because they have no implementation.

public abstract double calculateArea();


abstract

abstract
public abstract double calculatePerimeter();

abstract
public abstract String toString();
10
Constructing Polymorphism
• In Java, once you have the abstract method in a class, the entire class must
also be declared as an abstract class.

• An abstract class is a class that is declared with the reserve word


abstract in its heading.

• Example:
public abstract class AbstractClassExample
{
public abstract double calculateArea();
public abstract double calculatePerimeter();
public abstract String toString();
}

11
Constructing Polymorphism
• A class containing one or more abstract methods is called an
abstract class.

• An abstract class must be declared with a class-modifier


abstract.

• An abstract class is incomplete in its definition, since the


implementation of its abstract methods is missing. Therefore,
an abstract class cannot be instantiated. In other words, you
cannot create instances from an abstract class.

12
Constructing Polymorphism

• To use an abstract class, you have to derive a


subclass from the abstract class.

• In the derived subclass, you have to override


the abstract methods and provide
implementation to all the abstract methods. The
subclass derived is now complete and can be
instantiated.
13
Constructing Polymorphism
• Some facts about abstract class:
• Can contain • Can contain • If a class
instance variables, abstract methods. contains an
constructors, the abstract method,
finalizer, and then the class
nonabstract must be declared
methods. abstract.

• Cannot instantiate an • You can instantiate an


object of an abstract object of a subclass of
class. You can only an abstract class, but
declare a reference only if the subclass
variable of an gives the definition of all
the abstract methods of
abstract class type. the superclass.

14
Constructing Polymorphism
• If a class extends a class with an abstract
method and does not implement that abstract
method, then that method remains abstract in
the subclass. Consequently, the subclass is
also an abstract class and must be declared
abstract.

15
Constructing Polymorphism
(Example)
Calculate Area &
Triangle Circle
Perimeter

2D
What do you have to do?
Shape We need to list out
all attributes and methods
for each class.
Rectangle

16
Constructing Polymorphism
(Example)
Class: Rectangle Class: Triangle Class: Circle
Attributes: Attributes: Attributes:
 length  width (base)  radius
 width  height  area
 area  area  perimeter
 perimeter  perimeter

Methods: Methods: Methods:


 Setter for each attribute  Setter for each attributes  Setter for each attributes
 Getter for each attribute  Getter for each attributes  Getter for each attributes
 Processor for calculating  Processor for calculating  Processor for calculating
the area of a rectangle the area of a triangle the area of a circle
 Processor for calculating  Processor for calculating  Processor for calculating
the perimeter of a the perimeter of a triangle the perimeter of a circle
rectangle

17
Constructing Polymorphism
(Example)
ST
• Determine the common attributes and methods between classes
E
P
1 • Use polymorphism concept - Create a general class that will have only the
ST common attributes and methods/abstract method (without method body)
( abstract class)
E • Abstract methods refer to the method that will be used for all classes (specific
P class), but with different implementation such as the formula involved.

2
ST • Then we extend all the shape classes (specific class) from the general class
by using the inheritance concepts. (concrete class)
E • Write the methods’ definition for abstract method for each specific class.
P
3 18
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//To declare abstract object TwoD in a file named TwoD.java
//Put class TwoD in a package
package twoD;

//Class declaration and definition


public abstract class TwoD
{
protected double area;
protected double perimeter;

//Constructor
public TwoD()
{
area=0;
perimeter=0;
}

19
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//Getter or accessor methods
public double getArea(){return area;}

public double getPerimeter(){return perimeter;}

//Processor methods
public abstract void calculateArea();

public abstract void calculatePerimeter();

public abstract void display();


}

20
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
// To declare concrete object Rectangle in a file named
// Rectangle.java
//Put class Rectangle in a package
package twoD;

//class declaration and definition


public class Rectangle extends TwoD
{
private double width;
private double length;

//constructor
public Rectangle()
{
super();
width=0;
length=0;
}
21
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//setter or mutator methods
public void setWidth(double w)
{
width=w;
}

public void setLength(double l)


{
length=l;
}

//getter or accessor methods


public double getLength(){return length;}

public double getWidth(){return width;}

//processor methods
public void calculateArea()
{
area=length*width;
}
22
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
public void calculatePerimeter()
{
perimeter=2*length+2*width;
}

//printer methods
public void display()
{
System.out.println("RECTANGLE:");
System.out.println("The width : " +width);
System.out.println("The length : " +length);
System.out.println("The area : " +area)";
System.out.println("The perimeter: " +perimeter);

}
}

23
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//To declare concrete object Circle in a file named Circle.java
//put class circle in a package
package twoD;

//Class declaration and definition


public class Circle extends TwoD
{
private double radius;

//constructor
public Circle()
{
super();
radius=0;
}

//setter or mutator methods


public void setRadius(double r)
{
radius=r;
}
24
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//getter or accessor methods
public void calculateArea()
{
area=Math.PI*Math.pow(radius,2);
}

public void calculatePerimeter()


{
perimeter=2*Math.PI*radius;
}

//printer methods
public void display()
{
//Formating
DecimalFormat dF= new DecimalFormat("0.00");

System.out.println("CIRCLE: ");
System.out.println( "The radius : " +radius);
System.out.println("The area : " +dF.format(area));
System.out.println("The perimeter : "+dF.format(perimeter));
}
}

25
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//To declare object TestingTwoD.java in a file named TestingTwoD.java
import twoD.TwoD;
import twoD.Rectangle;
import twoD.Circle;

import java.util.*;

public class TestingTwoD


{
public static void main(String[] args)
{
Scanner scanner = new Scanner (System.in);

//To declare an array of TwoD


TwoD td[] = new TwoD[5];

26
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
for(int i=0; i<5; i++)
{
//display menu 1-rectangle 2-circle
System.out.print(("Your choice?(1/2)");
int c = scanner.nextInt();

if(c==1)
{
//input data
System.out.print("Input the width :");
double width = scanner.nextDouble();
System.out.print("Input the length :");
double len = scanner.nextDouble();

27
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
Rectangle rec = new Rectangle();
//Setting the data into an object
rec.setWidth(width);
rec.setLength(len);

//calculation
rec.calculateArea();
rec.calculatePerimeter();

//Store onto object


td[i] = rec;
}

else{
//input number as string
System.out.print("Input the radius :");
double radius = scanner.nextDouble();

//setting the data into an object


cir.setRadius(r); 28
Constructing Polymorphism
(Abstract and Concrete Class
Example 1)
//Calculation
cir.calculateArea();
cir.calculatePerimeter();

//Store onto object


td[i]=cir;
}
}

//to display - notice that we use the same method name


//for all classes
for(int j=0;j<3;j++)
{
td[j].display();
}
System.exit(0);
}
}
29
Array of Object from Abstract
Class
• Polymorphism allows a single variable to refer to objects from
different classes – the single variable can refer to any objects
from descendants’ classes

• Allow an array contains any object from descendants’ classes

• Example: Arrays’ declaration for abstract class

TwoD td[] = new TwoD[5];


Note: You are allowed to only have an arrays’ declaration but cannot
instantiate the array.
30
Array of Object from Abstract
Class
• Example: (from TestingTwoD.java). The declaration of array of object
(abstract class)
TwoD td[] = new TwoD[5];
0 1 2 3 4

Circle Rectangle Circle Rectangle Circle

• To display – notice that we use the j<5;


same j++)
method name for all classes
for(intj=0;
{
td[j].display();
}

• 31
The method display() – polymorphism method because it refers to
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//class privateInstitution - base case / general case
public abstract class privateInstitution
{
private String institutionName;
private char typeService;
private int noOfWorkers;
private int noOfCustomers;

//Default constructor
public privateInstitution()
{
institutionName = “”;
typeService = ‘ ’;
noOfWorkers = 0;
noOfCustomer = 0;
}
32
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Normal constructor
public privateInstitution(String instName,char typService,
int worker, int customer)
{
institutionName = instName;
typeService = typService;
noOfWorkers = worker;
noOfCustomer = customer;
}
//Mutator
public void setInstitutionName(String instName)
{ institutionName = instName; }
public char setTypeService(char typService)
{ typeService = typService; }
public void setNoOfWorkers(int worker)
{ noOfWorkers = worker; }
public int setNoOfCustomers()
{ noOfCustomers = customer; }
33
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Accessor
public String getInstitutionName()
{ return institutionName; }

public char getTypeService()


{ return typeService; }

public int getNoOfWorkers()


{ return noOfWorkers; }

public int getNoOfCustomers()


{ return noOfCustomers; }

//abstract methods
public abstract double calcProfit();
public abstract String toString();
}

34
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//class privateClinic - sub class/concrete class
public class privateClinic extends privateInstitution
{
final int Fewer_Rate = 15;
final int External_Rate = 120;
final int Diabetes_Rate = 52;
final int Blood_Rate = 45;
private String nameDoc;
private int time;

//Default constructor
public privateClinic()
{
super();
nameDoc = “”;
time = 0;
}

35
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Normal constructor
public privateClinic(String instName,char typService,
int worker, int customer, String nmDoc, int tm)
{
super(instName, typService, worker, customer);
nameDoc = nmDoc;
time = tm;
}

//Mutator
public void setNameDoctor(String nmDoc)
{ nameDoc = nmDoc; }

public void setTime(int tm)


{ time = tm; }

36
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Accessor
public String getNameDoctor()
{
return nameDoc;
}

public int getTime()


{
return time;
}

37
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//abstract method
public double calcProfit()
{
double value = 0.0;

switch(getTypeService())
{
case 'F': value = Fewer_Rate * getNoOfCustomers();
break;

case 'E': value = Externel_Rate * getNoOfCustomers();


break;

case 'D': value = Diabetes_Rate * getNoOfCustomers();


break;

case 'B': value = Blood_Rate * getNoOfCustomers();


break;
}
return value;
}
38
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Printer
public String toString()
{
return “\nInstitutionName: "+getInstitutinName()+"\n"+
"Type Service:"+getTypeService()+"\n"+
"No. Customer:"+getNoOfCustomers()+"\n"+
"No. Workers:"+getNoOfWorkers()+"\n"+
"Doctor Name:"+nameDoc+"\n"+"Time:"+time;
}
}

39
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//class privateCollege - sub class/concrete class
public class privateCollege extends privateInstitution
{
final int Computer_Rate = 2500;
final int Business_Rate = 2200;
final int Accounting_Rate = 2300;
final int Pra_Rate = 2700;
private String nameLec;

//Default constructor
public privateCollege()
{
super();
nameLec = “”;
}

40
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Normal constructor
public privateCollege(String instName, char typService,
int worker, int customer, String nmLec)
{
super(instName, typService, worker, customer);
nameLec = nmLec;
}

//Mutator
public void setNameLecturer(String nmLec)
{ nameLec = nmLec; }

//Accessor
public String getNameLecturer()
{ return nameLec; }
41
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Abstract method
public double calcProfit()
{
double value = 0.0;
switch(getTypeService())
{
case '1': value = Computer_Rate * getNoOfCustomers();
break;
case '2': value = Business_Rate * getNoOfCustomers();
break;
case '3': value = Acounting_Rate * getNoOfCustomers();
break;
case '4': value = Pra_Rate * getNoOfCustomers();
break;
}
return value;
}

42
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Printer
public String toString()
{
return “\nInstitutionName: "+getInstitutinName()+"\n"+
"Type Service:"+getTypeService()+"\n"+
"No.Customer:"+getNoOfCustomers()+"\n"+
"No. Workers:"+getNoOfWorkers()+"\n"+
“Lecturer Name:"+nameLec;
}
}

43
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Application program
public class privateInstitutionApp
{
public static void main(String[] args)
{
Scanner scanner = new Scanner (System.in);
String lineSeparator = System.getProperty(
"line.separator");
scanner.useDelimiter(lineSeparator);

System.out.print("Enter number of private institution: ");


int n = scanner.nextInt();

privateInstitution pi[] = new privateInstitution[n];

44
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
for(int j = 0; j<pi.length; j++)
{
System.out.print("Institution Name: ");
String instName= scanner.nextLine();
System.out.print("Service Type:");
String type = scanner.nextLine();
char typService = type.toUpperCase().charAt(0);
System.out.print("Number of workers: ");
int worker = scanner.nextInt()
System.out.print("Number of customer: ");
int customer = scanner.nextInt();

System.out.print("Type - (C)Clinic /" + "(L)College:");


String type = scanner.nextLine();
char privateType = type.toUpperCase().charAt(0);

45
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
if(privateType == 'C')
{
System.out.print("Doctor Name: ");
String nameDoc= scanner.nextLine();
System.out.print("Number of workers: ");
int tm = scanner.nextInt();

pi[j] = new privateClinic(instName, typService,


worker, customer, nameDoc, tm);
}
else
{
System.out.print("Lecturer Name: ");
String nameLec= scanner.nextLine();
pi[j] = new privateCollege(instName, typService,
worker,customer, nameLec);
}
}
46
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//to calculate total payment for private clinic and
//private college
double cliProfit = 0.0;
double clgProfit = 0.0;

for(int m = 0; m<pi.length; m++)


{
if(pi[m] instanceof privateClinic )
cliProfit += pi[m].calcProfit();
else
clgProfit += pi[m].calcProfit();
}
System.out.println ("Total of profit for all clinics: "
+cliProfit);
System.out.println("Total of profit for all colleges:”
+clgProfit);

47
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//the total of profit for diabetes treatment
double diaProfit = 0.0;

for(int m = 0; m<pi.length; m++)


{
if(pi[m] instanceof privateClinic )
{
if(pi[m].getTypeService() == 'D')
diaProfit += pi[m].calcProfit();
}
}
System.out.println("Total of profit for diabetes treatment: "
+diaProfit);

48
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//the average profit fees for all colleges
int noCollege = 0;
double allClgProfit = 0.0;

for(int m = 0; m<pi.length; m++)


{
if(pi[m] instanceof privateCollege)
{
noCollege++;
allClgProfit += pi[m].calcProfit();
}
}
System.out.println("Average profit fees for all colleges: "
+ allClgProfit/noCollege);

49
Constructing Polymorphism
(Abstract and Concrete Class
Example 2)
//Print information of clinic make profit >=5000
for(int m = 0; m<pi.length; m++)
{
if(pi[m] instanceof privateClinic)
{
if(pi[m].calProfit() >= 5000)
System.out.println(+pi[m].toString());
}
}

//Calculate the profit made by Dr. Saiful


double saifulProfit = 0.0;
for(int m = 0; m<pi.length; m++)
{
if(pi[m] instanceof privateClinic)
{ PrivateCinic pc = (PrivateClinic) pi[m]; //casting
if(pc.getNameDoctor().equals(“Dr. Saiful”)))
saifulProfit += pc.calcProfit();
}
}
System.out.println(“The profit made by Dr. Saiful: RM”+saifulProfit);
System.exit(0);
}
} 50
Summary
• An abstract class provides a template for further
development.

• The purpose of an abstract class is to provide a common


interface (or protocol, or contract, or understanding, or
naming convention) to all its subclasses.

• No implementation is possible. However, by specifying the


signature of the abstract methods, all the subclasses are
forced to use these methods' signature. The subclasses
could provide the proper implementations. 51
Summary
• Notes:
An abstract method cannot be declared final,
as final method cannot be overridden. An
abstract method, on the other hand, must be
overridden in a descendent before it can be
used.

An abstract method cannot be private (which


generates a compilation error). This is because
private method are not visible to the subclass
and thus cannot be overridden.

52
The End
Q&A
53

You might also like