OOPS Unit 1 Polymorphism
OOPS Unit 1 Polymorphism
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
What is Polymorphism?
• The human body has different organs. Every organ has a different
function to perform; the heart is responsible for blood flow, the lungs
for breathing, the brain for cognitive activity, and the kidneys for
excretion. So we have a standard method function that performs
differently depending upon the organ of the body.
Polymorphism in Java Example
c=a+b; System.out.println(c);
System.out.println(c);
public static void main(String[] args){
}
methodoverloading r=new methodoverloading();
void add(int x,int y){
r.add();//call add() method with no parameters
int c;
r.add(34,10); //call add() method with two int parameters
c=x+y;
r.add(16,10.5);//call add() method with int and double parameters
System.out.println("Addition Value of parameter int x =34 & int y=10 :
");
System.out.println(c); }
} }
Run Time Polymorphism in Java
Example class Main {
public class polymorphismshapes {
public void area() { public static void main(String[] args) {
System.out.println("The formula for area of "); polymorphismshapes myShape = new
polymorphismshapes();
}} // Create a polymorphismshapes class object
class Triangle extends polymorphismshapes{ polymorphismshapes myTriangle = new Triangle();
public void area(){ // Create a Triangle object
System.out.println("Triangle is ½ * base * height "); polymorphismshapes myCircle = new Circle();
}} // Create a Circle object
class Circle extends polymorphismshapes { myShape.area();
public void area() { myTriangle.area();
System.out.println("Circle is 3.14 * radius * radius "); myShape.area();
}} myCircle.area();
}}
Polymorphism in Java Example
• Output:
• The formula for the area of the Triangle is ½ * base * height
• The formula for the area of the Circle is 3.14 * radius * radius
• In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called
is based on the object being referred to by the reference variable.
• Upcasting
• If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting. For example
Run-Time Polymorphism