OOP - WK-13-Lec-25-26-Asg-12
OOP - WK-13-Lec-25-26-Asg-12
OOP - WK-13-Lec-25-26-Asg-12
Polymorphism
Week # 13 - Lecture 25 - 26
Spring 2020
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
2
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
You are required to implement a system where information of authors with their books has
been stored using the concept discussed in this lesson (Association, aggregation and
composition).
Author class contains author name (String), email (String), total number of written books with
following book detail.
Book class has book ID (String), Book Title (String), price (float) and publisher (String) has
attributes.
Associate these two classes with each other (according to your understanding) in a way that
user can get the information of author with detail of his total written books, like book title,
publisher, id and price. Demonstrate your program in main() function by creating an object of
class author with at least 3 books.
Note: Write setter and getter functions for both classes and also write appropriate
constructors.
Solution:
class Book{
String title, publisher, ID;
float price;
void setBook(){
System.out.println("Enter Book title: ");
Scanner s=new Scanner(System.in);
title=s.nextLine();
Scanner s1=new Scanner(System.in);
System.out.println("Enter Book Publisher: ");
publisher=s1.nextLine();
3
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
class Author {
String name, email;
int totalBooks;
Book books[];
void setAuthor(){
System.out.println("Enter Author name: ");
Scanner s=new Scanner(System.in);
name=s.nextLine();
System.out.println("Enter Author Email: ");
email=s.nextLine();
System.out.println("Enter total books written: ");
totalBooks=s.nextInt();
books=new Book[totalBooks];
for (int i=0;i<books.length; i++) {
books[i]=new Book();
books[i].setBook();
}
}
void getAuthor()
{
System.out.print(name+"\t"+email+"\t"+totalBooks+"\t");
class MAINCLASS{
public static void main(String[] args) {
Author a=new Author();
a.setAuthor();
a.getAuthor);
}
4
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Output
5
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
int a = 5;
int b = 6;
int sum = a + b; // Output = 11
And when we use + operator with strings, it performs string concatenation. For example,
Real life example of polymorphism: A person at the same time can have different
characteristic, like a man at the same time is a father, a husband, an employee, so the same
person posses different behavior in different situations. This is called polymorphism.
6
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
The word “poly” means many and “morphs” means forms, so it means many forms.
7
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Compile-time Polymorphism
Run-time Polymorphism
Method Overloading
In a Java class, we can create methods with the same name if they differ in parameters. For
example,
8
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
This is known as method overloading in Java. Let's take a working example of method
overloading.
class Demo {
public void displayPattern(){
for(int i = 0; i < 10; i++) {
System.out.print("* ");
}
}
class Main {
public static void main(String[] args) {
Demo d1 = new Demo();
d1.displayPattern();
System.out.println("\n");
d1.displayPattern('#');
}
}
Output:
* * * * * * * * * *
# # # # # # # # # #
If we call the method without passing any arguments, a pattern of * is created.
9
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
10
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
int a = 5;
int b = 6;
11
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
And when we use + operator with strings, it performs string concatenation. For example,
Note: In languages like C++, we can define operators to work differently for different
operands. However, Java doesn’t support user-defined operator overloading.
12
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the
overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding.
Method overriding on the other hand, occurs when a derived class has a definition for one
of the member functions of the base class. That base function is said to be overridden.
Suppose the same method is created in the superclass and its subclasses. In this case, the
method that will be called depends upon the object used to call the method.
13
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
class Doctor{
public void treatPatient() {
System.out.println("Doctor treatment..");
// treatment code goes here
}
}
class Surgeon extends Doctor {
public void treatPatient() {
System.out.println("Surgeon treatment..");
// treatment of surgeon goes here
}
}
class test{
public static void main (String args[]){
Output:
Doctor treatment..
Surgeon treatment..
14
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Ex:
class X{
public int sum(){
Ex: // some code
}
}
void sum (int a , int b);
void sum (int a , int b, int c);
class Y extends X{
void sum (float a, double b);
public int sum(){
//overridden method
//signature is same
}
}
15
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Here the reference variable "obj" is of the parent class, but the object it is pointing to is of the
child class (as shown in the diagram).
16
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
If a base class reference is used to call a method, the method to be invoked is decided by the
JVM, depending on the object the reference is pointing to.
For example, even though obj is a reference to Doctor, it calls the method of Surgeon, as it
points to a Surgeon object
What if the treatPatient method in the Surgeon class wants to execute the functionality
defined in Doctor class and then perform its own specific functionality?
In this case, keyword super can be used to access methods of the parent class from the child
class.
The treatPatient method in the Surgeon class could be written as:
treatPatient(){
super.treatPatient();
//add code specific to Surgeon
}
The keyword super can be used to access any data member or methods of the super class in
the sub class.
17
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
class Animal {
public void makeSound(){
System.out.println("Animal sound...");
}
}
18
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
}
}
Output:
But the call a.makeSound() calls method based on referenced class object
19
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
The method that will be called is determined during the execution of the program. Hence,
method overriding is a run-time polymorphism.
The operation of deposit and withdraw is same for Saving and Checking accounts. So the
inherited methods from Account class will work.
For a background, overdraft is a facility where you can withdraw an amount more than
available the balance in your account.
So, withdraw method for privileged needs to implemented afresh. But you do not change the
tested piece of code in Savings and Checking account. This is advantage of OOPS
20
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Step 1) Such that when the "withdrawn" method for saving account is called a method from
parent account class is executed.
Step 2) But when the "Withdraw" method for the privileged account (overdraft facility) is
called withdraw method defined in the privileged class is executed. This is Polymorphism.
21
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Difference between Static & Dynamic Polymorphism click here for video
Ex:
22
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
23
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Now, you study the following program carefully and try to determine its output −
24
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
Output
Constructing an Employee
Constructing an Employee
25
AJ/ Week 13-Lecture 25-26 Object Oriented Programming using Java (CS-423)
You are required to implement the above example of “bank” using the concept discussed in
this lesson (dynamic polymorphism).
Note: This is not your assignment of week 13, the only thing i want from you to practice the
topic for your better understanding.
26