Polymorphism Presentation 09
Polymorphism Presentation 09
Teacher Student
MANYFORM One person different
S behavior
Benefits:
Polymorphism allow one function or method to work in different ways
depending on context making code easier. In short, we can say same actions
in different ways.
Real Life Example:
Remote control
Output:-
Woof!
Meow!
thak gia hon juice pila do
yaar
Types of Polymorphism
There are two types of polymorphism.
1. Compile Time Polymorphism.
2. Run-Time polymorphism.
Compile Time Polymorphism
A polymorphism which exists at the time of compilation is called
compile time or static polymorphism .
Advantages:-
1. Type safety
2. Performance()
EXAMPLE:-
Method overloading:-
Whenever a class contain more than one method with same
name and different types of parameters is called overloading
Syntax
Void,
Array
return type method name(){….}
parameter
s
return type method name(){….}
Same
name
Code Example:
Class A{
void add(){
int a = 10 , b = 20 , c ;
c=a+b;
System.out.print( c ) ;
}
void add ( int x , double y ){
int c ;
c=x+y;
System.out.println( c );
}
Code Example:
void add ( int x , double y ){
double c ;
c=x+y;
System.out.println( c );
}
public static void main(String[] args){
A r=new A();
r.add();
r.add( 100 , 200 );
r.add( 10 , 35.40 );
}
}
Run-Time Polymorphism
Run-Time polymorphism happens when the program decides which
method to use while it is running. If a parent class reference is used to
call a method, the actual method that runs depends on which object
(either parent or child) the reference is pointing to at that moment.
This decision is made to runtime.
Example:
Method Overriding
Method overriding in Java is a feature that allows a subclass to
provide a specific implementation of a method that is already defined
in its superclass. It is used to modify or extend the functionality of an
inherited method.
Syntax:
public class MainClass {
public static void main(String[] args) {
superclass reference = new Subclass();
reference.methodName(parameters);
}}