SlideShare a Scribd company logo
POLYMORPHISM
Introduction
• Polymorphism is the ability of an object to take on many forms.
• In other words, polymorphism allows us to define one interface
and have multiple implementations.
• Polymorphism just means that, basically, once we have got a child
class, we can use objects of that child class wherever we would
use objects of the parent class. Java will automatically invoke the
right methods.
Introduction
So polymorphism can be elaborated as:
• It is a feature that allows one interface to be used for a general class
of actions.
• An operation may exhibit different behaviour in different instances.
• The behaviour depends on the types of data used in the operation.
• It plays an important role in allowing objects having different
internal structures to share the same external interface.
• Polymorphism is extensively used in implementing inheritance.
class Fruit {
public void show() {
System.out.println("Fruit");
}
}
class Banana extends Fruit {
//method overriden
public void show() {
System.out.println("Banana");
}
public void makeBananaTree() {
System.out.println("Making a tree");
}
}
public class Application {
public static void main(String[] args) {
Fruit banana = new Banana();
banana.show();
// The following WILL NOT work;
// Variables of type Fruit know only about Fruit methods.
banana.makeBananaTree();
}
} OUTPUT:
Banana
Introduction
class Shape { void draw() { } }
class Circle extends Shape {
private int x, y, r;
Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; }
void draw() { System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")"); }
}
class Rectangle extends Shape {
private int x, y, w, h;
Rectangle(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; }
void draw() { System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," + h + ")"); }
}
class ShapesMain {
public static void main(String[] args) {
Shape[] shapes = { new Circle(10, 20, 30),
new Rectangle(20, 30, 40, 50) };
for (int i = 0; i < shapes.length; i++)
shapes[i].draw();
}
}
Introduction
Types of Polymorphism in JAVA
Polymorphism
Method
Overloading
Method
Overriding
• In Java, it is possible to define two or more methods of same
name in a class, provided that there argument list or parameters
are different. This concept is known as Method Overloading.
Argument lists could differ in –
• Number of parameters.
• Data type of parameters.
• Sequence of Data type of parameters.
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example 1: Overloading – Different Number of parameters in argument list
When methods name are same but number of arguments are different.
class DisplayOverloading {
public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
}
class Sample {
public static void main(String args[]) {
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example 2: Overloading – Difference in data type of arguments
In this example, method disp() is overloaded based on the data type, one with char
argument and another with int argument.
class DisplayOverloading2{
public void disp(char c) {
System.out.println(c);
}
public void disp(int c) {
System.out.println(c);
}
}
class Sample2{
public static void main(String args[]) {
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example3: Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of arguments
class DisplayOverloading3 {
public void disp(char c, int num) {
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c) {
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3{
public static void main(String args[]) {
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:
I’m the first definition of method disp
I’m the second definition of method disp
Lets see few Valid/invalid cases of method
overloading
Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having
same number, data types and same sequence of data types in arguments.
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case for overloading. Here data types of arguments are
different.
Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case for overloading. Here number of arguments are
different.
Lets see few Valid/invalid cases of method
overloading
Case 4:
float mymethod(int a, float b)
float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case for overloading. Sequence of the data types are
different, first method is having (int, float) and second is having (float, int).
Case 5:
int mymethod(int a, int b)
float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even though return type of
methods are different, it is not a valid case. Since return type of method doesn’t matter
while overloading a method.
1. Overloaded method should always be the part of the same class
(can also take place in sub class), with same name but different
parameters.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. The parameters may differ in their type or number, or in both.
5. They may have the same or different return types.
Rules for Method Overloading
Guess the answers before checking it at the end
of programs
Question 1 – return type, method name and argument list same.
class Demo {
public int myMethod(int num1, int num2){
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2) {
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4 {
public static void main(String args[]) {
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}
Answer: It will throw a
compilation error: More than
one method with same name
and argument list cannot be
defined in a same class.
Question 2 – return type is different. Method name & argument list same.
class Demo2 {
public double myMethod(int num1, int num2) {
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2) {
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5 {
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
Guess the answers before checking it at the end
of programs
Answer: It will throw a
compilation error: More than one
method with same name and
argument list cannot be given in a
class even though their return
type is different. Method return
type doesn’t matter in case of
overloading.
• Declaring a method in subclass which is already present in
parent class is known as method overriding.
• The benefit of overriding is: ability to define a behaviour that's
specific to the subclass type which means a subclass can
implement a parent class method based on its requirement.
• In object-oriented terms, overriding means to override the
functionality of an existing method.
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
Output:
Animals can move
Dogs can walk and run
Consider the following example :
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
Consider the following example :
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
This would produce the following result:
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
This program will throw a compile time error since b's
reference type Animal doesn't have a bark method.
1. Applies only to inherited methods
2. Object type (NOT reference variable type) determines which
overridden method will be used at runtime
3. Overriding method can have different return type
4. Static and final methods cannot be overridden
5. Constructors cannot be overridden
6. It is also known as Runtime polymorphism.
Rules for Method Overriding

More Related Content

What's hot

Lisp
LispLisp
CFG to CNF
CFG to CNFCFG to CNF
CFG to CNF
Zain Ul Abiden
 
Why Python?
Why Python?Why Python?
Why Python?
Adam Pah
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Context free languages
Context free languagesContext free languages
Context free languages
Jahurul Islam
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
Animesh Sarkar
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
Tiji Thomas
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
Praveen M Jigajinni
 
Python
PythonPython
Python
SHIVAM VERMA
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
Java2Blog
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]
Alexander Hendorf
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
Sugantha T
 
Python libraries
Python librariesPython libraries
Python libraries
Venkat Projects
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
Karudaiyar Ganapathy
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
Ahmad Alhour
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
Intro C# Book
 
Python by Rj
Python by RjPython by Rj
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
Damian T. Gordon
 

What's hot (20)

Lisp
LispLisp
Lisp
 
CFG to CNF
CFG to CNFCFG to CNF
CFG to CNF
 
Why Python?
Why Python?Why Python?
Why Python?
 
Python basic
Python basicPython basic
Python basic
 
Context free languages
Context free languagesContext free languages
Context free languages
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python
PythonPython
Python
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
 
Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
 
Python libraries
Python librariesPython libraries
Python libraries
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 

Similar to Polymorphism.pptx

Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
Geekster
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
AndiNurkholis1
 
polymorphism method overloading and overriding .pptx
polymorphism method overloading  and overriding .pptxpolymorphism method overloading  and overriding .pptx
polymorphism method overloading and overriding .pptx
thamaraiselvangts441
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
Suresh Mohta
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
harsh kothari
 
Inheritance
InheritanceInheritance
Inheritance
Mavoori Soshmitha
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
nishajj
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or Functions
Kuppusamy P
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 

Similar to Polymorphism.pptx (20)

Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
 
polymorphism method overloading and overriding .pptx
polymorphism method overloading  and overriding .pptxpolymorphism method overloading  and overriding .pptx
polymorphism method overloading and overriding .pptx
 
Core java oop
Core java oopCore java oop
Core java oop
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Inheritance
InheritanceInheritance
Inheritance
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Hemajava
HemajavaHemajava
Hemajava
 
java poly ppt.pptx
java poly ppt.pptxjava poly ppt.pptx
java poly ppt.pptx
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or Functions
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 

Recently uploaded

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 

Recently uploaded (20)

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 

Polymorphism.pptx

  • 2. Introduction • Polymorphism is the ability of an object to take on many forms. • In other words, polymorphism allows us to define one interface and have multiple implementations. • Polymorphism just means that, basically, once we have got a child class, we can use objects of that child class wherever we would use objects of the parent class. Java will automatically invoke the right methods.
  • 3. Introduction So polymorphism can be elaborated as: • It is a feature that allows one interface to be used for a general class of actions. • An operation may exhibit different behaviour in different instances. • The behaviour depends on the types of data used in the operation. • It plays an important role in allowing objects having different internal structures to share the same external interface. • Polymorphism is extensively used in implementing inheritance.
  • 4. class Fruit { public void show() { System.out.println("Fruit"); } } class Banana extends Fruit { //method overriden public void show() { System.out.println("Banana"); } public void makeBananaTree() { System.out.println("Making a tree"); } } public class Application { public static void main(String[] args) { Fruit banana = new Banana(); banana.show(); // The following WILL NOT work; // Variables of type Fruit know only about Fruit methods. banana.makeBananaTree(); } } OUTPUT: Banana Introduction
  • 5. class Shape { void draw() { } } class Circle extends Shape { private int x, y, r; Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } void draw() { System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")"); } } class Rectangle extends Shape { private int x, y, w, h; Rectangle(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } void draw() { System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," + h + ")"); } } class ShapesMain { public static void main(String[] args) { Shape[] shapes = { new Circle(10, 20, 30), new Rectangle(20, 30, 40, 50) }; for (int i = 0; i < shapes.length; i++) shapes[i].draw(); } } Introduction
  • 6. Types of Polymorphism in JAVA Polymorphism Method Overloading Method Overriding
  • 7. • In Java, it is possible to define two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading. Argument lists could differ in – • Number of parameters. • Data type of parameters. • Sequence of Data type of parameters. Method Overloading (Compile-time Polymorphism or Static Polymorphism)
  • 8. Example 1: Overloading – Different Number of parameters in argument list When methods name are same but number of arguments are different. class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) { System.out.println(c + " "+num); } } class Sample { public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a',10); } } Output: a a 10 Method Overloading (Compile-time Polymorphism or Static Polymorphism)
  • 9. Example 2: Overloading – Difference in data type of arguments In this example, method disp() is overloaded based on the data type, one with char argument and another with int argument. class DisplayOverloading2{ public void disp(char c) { System.out.println(c); } public void disp(int c) { System.out.println(c); } } class Sample2{ public static void main(String args[]) { DisplayOverloading2 obj = new DisplayOverloading2(); obj.disp('a'); obj.disp(5); } } Output: a 5 Method Overloading (Compile-time Polymorphism or Static Polymorphism)
  • 10. Method Overloading (Compile-time Polymorphism or Static Polymorphism) Example3: Overloading – Sequence of data type of arguments Here method disp() is overloaded based on sequence of data type of arguments class DisplayOverloading3 { public void disp(char c, int num) { System.out.println("I’m the first definition of method disp"); } public void disp(int num, char c) { System.out.println("I’m the second definition of method disp" ); } } class Sample3{ public static void main(String args[]) { DisplayOverloading3 obj = new DisplayOverloading3(); obj.disp('x', 51 ); obj.disp(52, 'y'); } } Output: I’m the first definition of method disp I’m the second definition of method disp
  • 11. Lets see few Valid/invalid cases of method overloading Case 1: int mymethod(int a, int b, float c) int mymethod(int var1, int var2, float var3) Result: Compile time error. Argument lists are exactly same. Both methods are having same number, data types and same sequence of data types in arguments. Case 2: int mymethod(int a, int b) int mymethod(float var1, float var2) Result: Perfectly fine. Valid case for overloading. Here data types of arguments are different. Case 3: int mymethod(int a, int b) int mymethod(int num) Result: Perfectly fine. Valid case for overloading. Here number of arguments are different.
  • 12. Lets see few Valid/invalid cases of method overloading Case 4: float mymethod(int a, float b) float mymethod(float var1, int var2) Result: Perfectly fine. Valid case for overloading. Sequence of the data types are different, first method is having (int, float) and second is having (float, int). Case 5: int mymethod(int a, int b) float mymethod(int var1, int var2) Result: Compile time error. Argument lists are exactly same. Even though return type of methods are different, it is not a valid case. Since return type of method doesn’t matter while overloading a method.
  • 13. 1. Overloaded method should always be the part of the same class (can also take place in sub class), with same name but different parameters. 2. Constructor in Java can be overloaded 3. Overloaded methods must have a different argument list. 4. The parameters may differ in their type or number, or in both. 5. They may have the same or different return types. Rules for Method Overloading
  • 14. Guess the answers before checking it at the end of programs Question 1 – return type, method name and argument list same. class Demo { public int myMethod(int num1, int num2){ System.out.println("First myMethod of class Demo"); return num1+num2; } public int myMethod(int var1, int var2) { System.out.println("Second myMethod of class Demo"); return var1-var2; } } class Sample4 { public static void main(String args[]) { Demo obj1= new Demo(); obj1.myMethod(10,10); obj1.myMethod(20,12); } } Answer: It will throw a compilation error: More than one method with same name and argument list cannot be defined in a same class.
  • 15. Question 2 – return type is different. Method name & argument list same. class Demo2 { public double myMethod(int num1, int num2) { System.out.println("First myMethod of class Demo"); return num1+num2; } public int myMethod(int var1, int var2) { System.out.println("Second myMethod of class Demo"); return var1-var2; } } class Sample5 { public static void main(String args[]) { Demo2 obj2= new Demo2(); obj2.myMethod(10,10); obj2.myMethod(20,12); } } Guess the answers before checking it at the end of programs Answer: It will throw a compilation error: More than one method with same name and argument list cannot be given in a class even though their return type is different. Method return type doesn’t matter in case of overloading.
  • 16. • Declaring a method in subclass which is already present in parent class is known as method overriding. • The benefit of overriding is: ability to define a behaviour that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement. • In object-oriented terms, overriding means to override the functionality of an existing method. Method Overriding (Runtime Polymorphism or Dynamic Polymorphism )
  • 17. class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } } Method Overriding (Runtime Polymorphism or Dynamic Polymorphism ) Output: Animals can move Dogs can walk and run
  • 18. Consider the following example : class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } } Method Overriding (Runtime Polymorphism or Dynamic Polymorphism )
  • 19. Consider the following example : class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } } Method Overriding (Runtime Polymorphism or Dynamic Polymorphism ) This would produce the following result: TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark(); ^ This program will throw a compile time error since b's reference type Animal doesn't have a bark method.
  • 20. 1. Applies only to inherited methods 2. Object type (NOT reference variable type) determines which overridden method will be used at runtime 3. Overriding method can have different return type 4. Static and final methods cannot be overridden 5. Constructors cannot be overridden 6. It is also known as Runtime polymorphism. Rules for Method Overriding