7. Types Of Polymorphism
There are two types of polymorphism:
1.Compile Time Polymorphism:
2. Run Time Polymorphism:
8. 1.Compile Time Polymorphism:
Compile-time polymorphism is obtained through method overloading.
The term method overloading allows us to have more than one method
with the same name. Since this process is executed during compile
time, that is why it is known as Compile Time Polymorphism.
10. Example No:1
class test
{
void show ( int a ) // one argument
{
System.out.println ("1");
}
void show (String b ) // one argument
{
System.out.println ("2");
}
public static void main (String args[])
{
Test t =new Test();
t.show (10);
}
}
OUTPU
T
1
11. Example No:2
class test
{
void show ( int a , String b) // two arguments
{
System.out.println ("1");
}
void show (String a, int b ) // two arguments
{
System.out.println ("2");
}
public static void main (String args[])
{
Test t =new Test();
t.show (10 , “abc”);
}
}
OUTPU
T
1
12. What is RunTime Polymorphism
Method overriding is an example of runtime
polymorphism. In method overriding, a subclass overrides
a method with the same signature as that of in its
superclass. During compile time, the check is made on the
reference type.
13. • When a chlid class extands a parent class the
all of its variable and method is accessible in
the child class. But when the child class
overrides one of the method of the parent class,
then during the runtime the method of child class
is called rather than the parent class, this is
decided in the run time and not in the compile
time.
14. EXAMPLE
class Animal {
void makesound() {
System.out.println("animal makes a sound");
}
}
class dog extends Animal {
void makesound() {
System.out.println("dog barks");
}
}
class cat extends Animal {
void makesound() {
System.out.println("cat meows");
}
}
public class main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makesound();
animal2.makesound();
}
}
OUTPUT
Dog barks
Cat meows
15. In this example, both the Dog and Cat classes override the make
Sound method inherited from the Animal class. When you create
instances of Dog and Cat and call the make Sound method on
them, the appropriate overridden method is invoked based on their
actual runtime types.