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

Lecture 12 Polymorphism

oop

Uploaded by

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

Lecture 12 Polymorphism

oop

Uploaded by

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

Lecture#12

Polymorphism

Course: Object oriented Programming (CE-225)


Course Teacher: Dr Umm-e-Laila& Ms.Aneeta Siddiqui

Contact Info:
Room No: BS-04, CED
1 Email: [email protected]
Course Books

 Text Book:
 Herbert Schildt, Java: The Complete Reference, 12th
Edition ,McGraw-Hill Education.
 Deitel, Paul, Java How to Program, 11th Edition, Pearson,
2017

 Reference Books:
 Horton, Ivor, Beginning Java, 7th Edition, Wrox, 2011

2
Course Instructors

 Dr. Umm-e-Laila [email protected]


Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536

 Aneeta Siddiqui [email protected]


Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Marks Distribution

Assignments + Quiz ______________

20

Mid Term ______________

30

Semester Final Paper ______________


4
50
Topics Covered

 Polymorphism
 Types of Polymorphism
 Run time Polymorphism
 Compile time Polymorphism
 Upcasting
 Java Runtime Polymorphism Example:
Bank
 Java Runtime Polymorphism with Data
Member
 Java Runtime Polymorphism with
5
Multilevel Inheritance
6 Polymorphism
 Polymorphism is one of the object oriented programming feature that
allows us to perform a single action in different ways.
 For example, lets say we have a class Animal that has a method
sound(). Since this is a generic class so we can’t give it a
implementation like: Roar, Meow, Oink etc. We had to give a generic
message..
7 Polymorphism Example

# Example 01

public class Animal{


...
public void sound(){
System.out.println("Animal is making a sound");
}
}

Now lets say we two subclasses of Animal


class: Horse and Cat that extends Animal
class. We can provide the implementation to
the same method like this:
8 Polymorphism Example
# Example 01
public class Horse extends Animal{
...
@Override
public void sound(){
System.out.println("Neigh");
}
}

and
# Example 01
public class Cat extends Animal{
...
@Override
public void sound(){
System.out.println("Meow");
}
}
9 Polymorphism
 As you can see that although we had the common action for all
subclasses sound().
 But there were different ways to do the same action. This is a perfect
example of polymorphism
 Feature that allows us to perform a single action in different ways
10 Polymorphism
 It would not make any sense to just call the generic sound() method
 As each Animal has a different sound.
 Thus we can say that the action this method performs is based on the
type of object.
11 Polymorphism in Programming
 Polymorphism is the capability of a method to do different things
based on the object that it is acting upon.
 In other words, polymorphism allows you define one interface and
have multiple implementations.
 As we have seen in the above example that we have defined the
method sound() and have the multiple implementations of it in the
different-2 sub classes.
12 Polymorphism in Programming
 Which sound() method will be called is determined at runtime so the
example we gave above is a runtime polymorphism example.
UML Diagram: Rectangle
13

What if we want to implement a 3d box object?


Objects myRectangle and myBox
14

Rectangle myRectangle = new Rectangle(5, 3);


Box myBox = new Box(6, 5, 4);
UML
15 Class Diagram: class Box

Both a Rectangle and a Box have a surface area,


but they are computed differently
16
class Rectangle

public double area()


{
return getLength() * getWidth();
}

class Box
public double area()
{
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}
final Methods
17

 Can declare a method of a class final using the keyword final

public final void doSomeThing()


{
//...
}

 If a method of a class is declared final, it cannot be overridden


with a new definition in a derived class
Calling methods of the superclass
18
 To write a method’s definition of a subclass, specify a call to the
public method of the superclass
 If subclass overrides public method of superclass, specify call to public method of superclass:
super.MethodName(parameter list)
 If subclass does not override public method of superclass, specify call to public method of
superclass:
MethodName(parameter list)
class Box
19

public void setDimension(double l, double w, double h)


{
super.setDimension(l, w);
if (h >= 0)
height = h;
else
height = 0;
}}

Box overloads the method setDimension


(Different parameters)
Defining Constructors of the Subclass
20

 Call to constructor of superclass:


 Must be first statement
 Specified by super parameter list

public Box()
{
super();
height = 0;
}

public Box(double l, double w, double h)


{
super(l, w);
height = h;
}
21 Access Control

 Access control keywords define which classes can


access classes, methods, and members

Modifier Class Package Subclass World


public Y Y Y Y
protected Y Y Y N
none Y Y N N
private Y N N N
22 Types of Polymorphism

1. Method Overloading in Java – This is an example of compile time


(or static polymorphism)

2. Method Overriding in Java – This is an example of runtime time (or


dynamic polymorphism)
23 Run Time Polymorphism Example

class Horse extends Animal{


# Example @Override
public void sound(){
public class Animal{ System.out.println("Neigh");
public void sound(){ }
System.out.println("Animal is public static void main(String
making a sound"); args[]){
} Animal obj = new Horse();
} obj.sound();
}
}
24 Run Time Polymorphism Example
# Example

public class Animal{ class Horse extends Animal{


public void sound(){ @Override
System.out.println("Animal is public void sound(){
making a sound"); System.out.println("Neigh");
} }
} public static void main(String
args[]){
Animal obj = new Horse();
obj.sound();
Output: }
}
Neigh
25 Run Time Polymorphism Example

public class Cat extends Animal{ Output:


@Override
public void sound(){ Meow
System.out.println("Meow");
}
public static void main(String args[]){
Animal obj = new Cat();
obj.sound();
}
}
26 Compile Time Polymorphism
Example
class Overload
{ class MethodOverloading
void demo (int a)
{
{
System.out.println ("a: " + a); public static void main (String args
} [])
void demo (int a, int b) {
{ Overload Obj = new Overload();
System.out.println ("a and b: " + a + double result;
"," + b); Obj .demo(10);
} Obj .demo(10, 20);
double demo(double a) {
System.out.println("double a: " +
result = Obj .demo(5.5);
a); System.out.println("O/P : " +
return a*a; result);
} }
} }
27 Compile Time Polymorphism
Example
class Overload
{ class MethodOverloading
void demo (int a)
{
{
System.out.println ("a: " + a); public static void main (String args
} Output: [])
void demo (int a, int b) {
{ a: 10 Overload Obj = new Overload();
System.out.printlna("a
andandb:b:10,20
"+a+ double result;
"," + b); Obj .demo(10);
} double a: 5.5
O/P Obj .demo(10, 20);
double demo(double a) { : 30.25
System.out.println("double a: " +
result = Obj .demo(5.5);
a); System.out.println("O/P : " +
return a*a; result);
} }
} }
28 Upcasting
 If the reference variable of Parent class
refers to the object of Child class, it is
known as upcasting. For example:
Polymorphism and References
29

Shape myShape = new Circle(); // allowed


Shape myShape2 = new Rectangle(); // allowed
Rectangle myRectangle = new Shame(); // NOT allowed
30 Upcasting

class A{}
class B extends A{}
A a=new B();//upcasting

• For upcasting, we can use the reference


variable of class type or an interface type.
Casting
31

 You cannot automatically make reference


variable of subclass type point to object of
its superclass
 Suppose that supRef is a reference variable
of a superclass type and supRef points to
an object of its subclass:
 Can use a cast operator on supRef and make a
reference variable of the subclass point to the
object
 If supRef does not point to a subclass object and
you use a cast operator on supRef to make a
reference variable of the subclass point to the
object, then Java will throw a
ClassCastException—indicating that the class
cast is not allowed
Polymorphism (continued)
32

 Operator instanceof: determines whether a reference variable that


points to an object is of a particular class type

 This expression evaluates to true if p points to an object of the


class BoxShape; otherwise it evaluates to false:

p instanceof BoxShape
33 Upcasting
class Bike{  In this example,
void run()
{System.out.println("running");}
we are creating
} two classes Bike
class Splendor extends Bike{
void run() and Splendor.
{System.out.println("running safely  Splendor class
with 60km");}
extends Bike
public static void main(String args[]) class and
{
Bike b = new overrides its run()
Splendor();//upcasting
b.run();
method.
}  We are calling
}
the run method
by the reference
variable of Parent
34 Upcasting
class Bike{  Since it refers to
void run()
{System.out.println("running");}
the subclass
} object and
class Splendor extends Bike{
void run() subclass method
{System.out.println("running safely overrides the
with 60km");}
Parent class
public static void main(String args[]) method, the
{
Bike b = new subclass method
Splendor();//upcasting
b.run();
is invoked at
} runtime.
}  Since method
invocation is
determined by
35 Upcasting
class Bike{  Since method
void run()
{System.out.println("running");}
invocation is
} determined by
class Splendor extends Bike{
void run() the JVM not
{System.out.println("running safely compiler, it is
with 60km");}
known as
public static void main(String args[]) runtime
{
Bike b = new polymorphism.
Output:
Splendor();//upcasting
b.run(); running safely with
} 60km.
}
36 Example Casting
public class Animal {
String name="Animal";
public void sound();
{ public class Dog extends
Animal {
System.out.println("Animal
String name=“Dog";
Sound");
@Override
}}
public void sound(){
public class Duck extends
System.out.println("Dog
Animal {
Sound");
String name="Duck"; }
@Override }
public void sound(){ public class Cat extends
System.out.println("Duck Animal {
Sound"); String name=“Cat";
} @Override

public void CanSwim(){ public void sound(){


System.out.println(“Cat
37 Example Casting
public class Checkanimal { for (Animal arr1 : arr) {
public static void arr1.sound();
main(String[] args) { if(arr1 instanceof Duck){
Animal arr[]=new
Animal[4]; Duck obj=(Duck)(arr1);
Animal a=new Animal(); downcasting
Cat c=new Cat(); obj.CanSwim();
Dog d=new Dog(); }
Duck du=new Duck(); c.sound();
arr[0]=a; d.sound();
arr[1]=c; c.name="abc";
arr[2]=d;
arr[3]=du; System.out.println(""+c.name)
a=c; //upcasting ;
a.sound(); }
System.out.println(""+a.nam }
e);
c=(Cat)(a);

System.out.println(""+c.nam
e);
38 Java Runtime Polymorphism
Example: Bank
 Consider a scenario where Bank is a class that provides a method to
get the rate of interest.
 However, the rate of interest may differ according to banks. For
example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and
9.7% rate of interest.
39 Java Runtime Polymorphism
Example: Bank
40 Java Runtime Polymorphism
Example: Bank
class TestPolymorphism{
public static void main(String args[]){
class Bank{
Bank b;
float getRateOfInterest(){return 0;}
b=new SBI();
}
System.out.println("SBI Rate of Interest:
class SBI extends Bank{
"+b.getRateOfInterest());
float getRateOfInterest(){return 8.4f;}
b=new ICICI();
}
System.out.println("ICICI Rate of
class ICICI extends Bank{
Interest: "+b.getRateOfInterest());
float getRateOfInterest(){return 7.3f;}
b=new AXIS();
}
System.out.println("AXIS Rate of
class AXIS extends Bank{
Interest: "+b.getRateOfInterest());
float getRateOfInterest(){return 9.7f;}
}
}
}
41 Java Runtime Polymorphism
Example: Bank
class TestPolymorphism{
public static void main(String args[]){
class Bank{
Bank b;
float getRateOfInterest(){return 0;}
b=new SBI();
}
System.out.println("SBI Rate of Interest:
class SBI extends Bank{
Output: "+b.getRateOfInterest());
float getRateOfInterest(){return 8.4f;}
b=new ICICI();
}
SBI Rate of Interest: 8.4 System.out.println("ICICI Rate of
class ICICI extends Bank{
ICICI Rate of Interest: 7.3
float getRateOfInterest(){return 7.3f;}
Interest: "+b.getRateOfInterest());
AXIS Rate of Interest: 9.7 b=new AXIS();
}
System.out.println("AXIS Rate of
class AXIS extends Bank{
Interest: "+b.getRateOfInterest());
float getRateOfInterest(){return 9.7f;}
}
}
}
42 Java Runtime Polymorphism with
Data Member

 A method is overridden, not the data members, so runtime


polymorphism can't be achieved by data members.
43 Java Runtime Polymorphism with
Data Member
 In the example, both the classes
have a data member speedlimit.
class Bike{  We are accessing the data
int speedlimit=90; member by the reference
} variable of Parent class which
class Honda3 extends Bike{ refers to the subclass object.
int speedlimit=150;

public static void main(String args[]){

Bike obj=new Honda3();

System.out.println(obj.speedlimit);//90

}
44 Java Runtime Polymorphism with
Data Member
 Since we are accessing the data
member which is not overridden,
class Bike{ hence it will access the data
int speedlimit=90; member of the Parent class
} always.
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){

Bike obj=new Honda3();

System.out.println(obj.speedlimit);//90

}
45 Java Runtime Polymorphism with
Data Member
 Since we are accessing the data
member which is not overridden,
class Bike{ hence it will access the data
int speedlimit=90; member of the Parent class
} always.
class Honda3 extends Bike{
int speedlimit=150;
Output:
public static void main(String args[]){
90
Bike obj=new Honda3();

System.out.println(obj.speedlimit);//90

}
46 Java Runtime Polymorphism with
Multilevel Inheritance

class Animal{ public static void main(String args[]){


void eat() Animal a1,a2,a3;
{System.out.println("eating");} a1=new Animal();
} a2=new Dog();
class Dog extends Animal{ a3=new BabyDog();
void eat(){System.out.println("eating a1.eat();
fruits");} a2.eat();
} a3.eat();
class BabyDog extends Dog{ }
void eat(){System.out.println("drinking }
milk");}
47 Java Runtime Polymorphism with
Multilevel Inheritance

class Animal{ public static void main(String args[]){


void eat() Animal a1,a2,a3;
{System.out.println("eating");} a1=new Animal();
} Output: a2=new Dog();
class Dog extends Animal{ a3=new BabyDog();
eating
void eat(){System.out.println("eating a1.eat();
fruits");} eating fruits a2.eat();
} drinking Milk a3.eat();
class BabyDog extends Dog{ }
void eat(){System.out.println("drinking }
milk");}
48 Composition

 Another way to relate two classes


 One or more members of a class are objects of
another class type
 “has-a” relation between classes
 For example, “every person has a date of birth”
Composition Example
49
Summary

 Polymorphism allows objects to represent


instances of its own class and any of its
sublcasses.

 Polymorphic collections are useful for


managing objects with common (ancestor)
interfaces.

 For our purposes, we’ll assume objects


“remember” what kind of class they really
contain, so method calls are resolved to the
original class.

You might also like