Polymorph Is Im
Polymorph Is Im
OOP (JAVA)
INTRODUCTION TO POLYMORPHISM
TYPES OF POLYMORPHISM
METHOD OVERLOADING
METHOD OVERRIDING
EXAMPLES
RUN TIME POLYMORPHISM OR DYNAMIC DISPATCH METHOD
POLYMORPHISM
class Adder{
static int add(int a,int b){return a+b;}
In java, method overloading is not static double add(int a,int b){return a+b;}
possible by changing the return type of
the method only because of ambiguity. }
Let's see how ambiguity may occur
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
CAN WE OVERLOAD JAVA MAIN() METHOD?
Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only. Let's see the simple example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
METHOD OVERLOADING AND TYPE PROMOTION
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
• Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
• Method overriding is used for runtime polymorphism
RULES FOR JAVA METHOD OVERRIDING
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
A REAL EXAMPLE OF JAVA METHOD OVERRIDING