in java Explain why and give examples In OO programming Poly
in java Explain why and give examples. “In OO programming Polymorphism is only possible when using Interface or Inheritance” .
Solution
Polymorphism: Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word \"poly\" means many and \"morphs\" means forms. So polymorphism means many forms.
(or)
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
Compile time polymorphism is nothing but the method overloading in java. In simple terms we can say that a class can have more than one methods with same name but with different number of arguments or different types of arguments or both. To know more about it refer method overloading in java.
example:
Runtime Polymorphism :
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
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.
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
Example program:
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test3{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println(\"SBI Rate of Interest: \"+b1.getRateOfInterest());
System.out.println(\"ICICI Rate of Interest: \"+b2.getRateOfInterest());
System.out.println(\"AXIS Rate of Interest: \"+b3.getRateOfInterest());
}
}

