SlideShare a Scribd company logo
Inheritance
&
Polymorphism
Inheritance & OOP
• In java inheritance means deriving a class from existing class.
• This allows us to reuse code.
• We can use fields & methods from the existing class, because it is reusable.
• For example, the child inherits from his/her parents.
• The existing class called super class & the deriving class called subclass.
o Subclass (child): the class that inherits from another class
o Super class (parent): the class being inherited from
The Object Class
• As we will see, we can derive one class from another. For example, suppose we write a class called Product
for a sports shop.
• Basketball is a Product but is more specific than simply a Product.
• So, we can say following:
o Product is a class and has functionality that any products have.
o Basketball is a class and has all the functionality of a Product but perhaps more.
• So, the product is a super/base/parent class and the basketball is a child/sub class.
Example of Inheritance
• Polygon is the base/super/parent class. Learn these 3
terms!!
o Triangle “is a” Polygon and Rectangle “is a” Polygon.
o Square “is a” special Rectangle.
• We programming types use these terms:
o base, super or parent class
o child, sub, or derived class
o is a
Polymorphism
• Polymorphism is the ability of an object to take on many forms.
• It allows us to call superclass method from a derived class because of the “is a” relationship.
• We showed that inheritance lets us inherit attributes and methods from another class. Polymorphism uses
those methods to perform different tasks. This allows us to perform a single action in different ways.
• For example:
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
• Now, the Deer class is polymorphic since this has multiple inheritance. Following are true for the above
examples:
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
Example of Polymorphism
• Superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats,
Dogs; And they also have their own implementation of an animal sound (the pig oinks, cat meows, etc.):
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
• Now we can create Pig and Dog objects and call the animalSound() method on both of them:
• For Example:
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Continued to next page . . .
class MyMainClass {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create an Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Ad

More Related Content

Similar to Inheritance & Polymorphism (20)

Inheritance and polymorphism
Inheritance and polymorphism   Inheritance and polymorphism
Inheritance and polymorphism
baabtra.com - No. 1 supplier of quality freshers
 
Ayan Das_25300121057.pptx
Ayan Das_25300121057.pptxAyan Das_25300121057.pptx
Ayan Das_25300121057.pptx
Ayan974999
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
Vikash Dúbēy
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
HARIPRIYA M P
 
Inheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python ProgrammingInheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Understanding_of_Inheritance_in_Java_by_Quipoin.pptx
Understanding_of_Inheritance_in_Java_by_Quipoin.pptxUnderstanding_of_Inheritance_in_Java_by_Quipoin.pptx
Understanding_of_Inheritance_in_Java_by_Quipoin.pptx
quipoin04
 
Object Oriented Programming -Single Inheritance.pptx
Object Oriented Programming -Single Inheritance.pptxObject Oriented Programming -Single Inheritance.pptx
Object Oriented Programming -Single Inheritance.pptx
jospinjj
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
88 Inheritance - Part 1.pptx
88 Inheritance - Part 1.pptx88 Inheritance - Part 1.pptx
88 Inheritance - Part 1.pptx
NileshKumar419531
 
Inheritance in Java.pdf
Inheritance in Java.pdfInheritance in Java.pdf
Inheritance in Java.pdf
kumari36
 
03-inheretance java code programming .pdf
03-inheretance java code programming .pdf03-inheretance java code programming .pdf
03-inheretance java code programming .pdf
sithumMarasighe
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptx
ShuvrojitMajumder
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
inheritance-16031525566nbhij56604452.pdf
inheritance-16031525566nbhij56604452.pdfinheritance-16031525566nbhij56604452.pdf
inheritance-16031525566nbhij56604452.pdf
kashafishfaq21
 
Chapter 04 Object Oriented programming .pptx
Chapter 04 Object Oriented programming .pptxChapter 04 Object Oriented programming .pptx
Chapter 04 Object Oriented programming .pptx
fikadumeuedu
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
Ayan Das_25300121057.pptx
Ayan Das_25300121057.pptxAyan Das_25300121057.pptx
Ayan Das_25300121057.pptx
Ayan974999
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
Vikash Dúbēy
 
Inheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python ProgrammingInheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Understanding_of_Inheritance_in_Java_by_Quipoin.pptx
Understanding_of_Inheritance_in_Java_by_Quipoin.pptxUnderstanding_of_Inheritance_in_Java_by_Quipoin.pptx
Understanding_of_Inheritance_in_Java_by_Quipoin.pptx
quipoin04
 
Object Oriented Programming -Single Inheritance.pptx
Object Oriented Programming -Single Inheritance.pptxObject Oriented Programming -Single Inheritance.pptx
Object Oriented Programming -Single Inheritance.pptx
jospinjj
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
Gina Bullock
 
88 Inheritance - Part 1.pptx
88 Inheritance - Part 1.pptx88 Inheritance - Part 1.pptx
88 Inheritance - Part 1.pptx
NileshKumar419531
 
Inheritance in Java.pdf
Inheritance in Java.pdfInheritance in Java.pdf
Inheritance in Java.pdf
kumari36
 
03-inheretance java code programming .pdf
03-inheretance java code programming .pdf03-inheretance java code programming .pdf
03-inheretance java code programming .pdf
sithumMarasighe
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptx
ShuvrojitMajumder
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
inheritance-16031525566nbhij56604452.pdf
inheritance-16031525566nbhij56604452.pdfinheritance-16031525566nbhij56604452.pdf
inheritance-16031525566nbhij56604452.pdf
kashafishfaq21
 
Chapter 04 Object Oriented programming .pptx
Chapter 04 Object Oriented programming .pptxChapter 04 Object Oriented programming .pptx
Chapter 04 Object Oriented programming .pptx
fikadumeuedu
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 

More from SAGARDAVE29 (12)

Graphical User Interface (GUI)
Graphical User Interface (GUI)Graphical User Interface (GUI)
Graphical User Interface (GUI)
SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Exception Handling
Exception HandlingException Handling
Exception Handling
SAGARDAVE29
 
JAVA Multithreading
JAVA MultithreadingJAVA Multithreading
JAVA Multithreading
SAGARDAVE29
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
SAGARDAVE29
 
Exception handling
Exception handlingException handling
Exception handling
SAGARDAVE29
 
More oop in java
More oop in javaMore oop in java
More oop in java
SAGARDAVE29
 
Coding Style & Tips for JAVA
Coding Style & Tips for JAVACoding Style & Tips for JAVA
Coding Style & Tips for JAVA
SAGARDAVE29
 
Some Important Methods in JAVA
Some Important Methods in JAVASome Important Methods in JAVA
Some Important Methods in JAVA
SAGARDAVE29
 
Recursion
RecursionRecursion
Recursion
SAGARDAVE29
 
Graphical User Interface (GUI)
Graphical User Interface (GUI)Graphical User Interface (GUI)
Graphical User Interface (GUI)
SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Exception Handling
Exception HandlingException Handling
Exception Handling
SAGARDAVE29
 
JAVA Multithreading
JAVA MultithreadingJAVA Multithreading
JAVA Multithreading
SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Exception handling
Exception handlingException handling
Exception handling
SAGARDAVE29
 
More oop in java
More oop in javaMore oop in java
More oop in java
SAGARDAVE29
 
Coding Style & Tips for JAVA
Coding Style & Tips for JAVACoding Style & Tips for JAVA
Coding Style & Tips for JAVA
SAGARDAVE29
 
Some Important Methods in JAVA
Some Important Methods in JAVASome Important Methods in JAVA
Some Important Methods in JAVA
SAGARDAVE29
 
Ad

Recently uploaded (20)

How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Ad

Inheritance & Polymorphism

  • 2. Inheritance & OOP • In java inheritance means deriving a class from existing class. • This allows us to reuse code. • We can use fields & methods from the existing class, because it is reusable. • For example, the child inherits from his/her parents. • The existing class called super class & the deriving class called subclass. o Subclass (child): the class that inherits from another class o Super class (parent): the class being inherited from
  • 3. The Object Class • As we will see, we can derive one class from another. For example, suppose we write a class called Product for a sports shop. • Basketball is a Product but is more specific than simply a Product. • So, we can say following: o Product is a class and has functionality that any products have. o Basketball is a class and has all the functionality of a Product but perhaps more. • So, the product is a super/base/parent class and the basketball is a child/sub class.
  • 4. Example of Inheritance • Polygon is the base/super/parent class. Learn these 3 terms!! o Triangle “is a” Polygon and Rectangle “is a” Polygon. o Square “is a” special Rectangle. • We programming types use these terms: o base, super or parent class o child, sub, or derived class o is a
  • 5. Polymorphism • Polymorphism is the ability of an object to take on many forms. • It allows us to call superclass method from a derived class because of the “is a” relationship. • We showed that inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. • For example: public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} • Now, the Deer class is polymorphic since this has multiple inheritance. Following are true for the above examples: A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object
  • 6. Example of Polymorphism • Superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs; And they also have their own implementation of an animal sound (the pig oinks, cat meows, etc.): class Animal { public void animalSound() { System.out.println("The animal makes a sound"); } } class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } } class Dog extends Animal { public void animalSound() { System.out.println("The dog says: bow wow"); } }
  • 7. • Now we can create Pig and Dog objects and call the animalSound() method on both of them: • For Example: class Animal { public void animalSound() { System.out.println("The animal makes a sound"); } } class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } } class Dog extends Animal { public void animalSound() { System.out.println("The dog says: bow wow"); } } Continued to next page . . .
  • 8. class MyMainClass { public static void main(String[] args) { Animal myAnimal = new Animal(); // Create an Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } }