Chapter 4
Chapter 4
Chapter 3
Inheritance & Polymorphism II
1. Polymorphism
2. Advantages of Polymorphism in Java
3. Disadvantages of Polymorphism in Java
4. Polymorphism Examples
5. Method Overloading and Method Overriding
6. More Example
Contents
Recommended Reading
1. Java Inheritance:
https://www.tutorialspoint.com/java/java_inheritance.htm
• Polymorphism
Polymorphism
• Polymorphism: many forms.
Polymorphism
• Polymorphism
• means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
• Polymorphism uses those methods to perform different tasks. This allows us
to perform a single action in different ways.
• Requires that there be multiple methods of the same name.
• Advantages:
1.Increases code reusability by allowing objects of different classes to be treated as
objects of a common class.
• Disadvantages:
1.Can make it more difficult to understand the behavior of an object, especially if
the code is complex.
Method Overloading
• Defined as a process that can create multiple methods of the
same name in the same class, and all the methods work in
different ways.
• Method overloading occurs when there is more than one method
of the same name in the class
Method Overriding
• Defined as a process when the subclass or a child class has the
same method as declared in the parent class.
Reference: https://www.mygreatlearning.com/blog/polymorphism-in-java/
Method Overloading and Method Overriding
• Method Overloading Example:
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }
Output
public static void main(String args[]){
Car2 obj = new Car2(); Car is running safely
obj.run();//calling method
}
}
Reference: https://www.mygreatlearning.com/blog/polymorphism-in-java/
Method Overloading and Method Overriding
class A{}
class B extends A{}
A a=new B(); //upcasting
Reference: https://www.mygreatlearning.com/blog/polymorphism-in-java/
More Example
• Example: class main{
public static void main(String args[]){
class Animal { Animal A = new Animal();
void eat(){ Animal h = new herbivores(); //upcasting
System.out.println("Animals Eat");
} Animal o = new omnivores(); //upcasting
} Animal c = new carnivores(); //upcasting
class herbivores extends Animal{ A.eat();
h.eat();
void eat(){
o.eat();
System.out.println("Herbivores Eat Plants"); c.eat();
}
} }
}
class omnivores extends Animal{
void eat(){
System.out.println("Omnivores Eat Plants and meat"); Output
}
}
class carnivores extends Animal{ Animals eat
void eat(){ Herbivores Eat Plants
System.out.println("Carnivores Eat meat"); Omnivores Eat Plants and meat
}
} Carnivores Eat meat
Reference: https://www.mygreatlearning.com/blog/polymorphism-in-java/
Thank You