Core Java SQL Oracle PHP Examples JSP JDBC MORE

Java Runtime polymorphism


poly morphism:

In java run time polymorphism is one thing that show multiple behaviour ,poly morphism is derived from Greek word :poly means many morphism means behaviour

Run time poly morphism:

It is the process in which a call to an overridden method is resolved at runtime rather than runtime.

In this an overridden method is called through the reference variable of parent class.

Syntax of run time Polymorphism

class G{}
class H extends G{}
G g=new H();

Example of runtime polymorphism

class Fruit{
void run(){System.out.println("eating");}
}
class Apple extends Fruit{
void run(){System.out.println("it is very good for health");}
public static void main(String args[]){
Fruit p = new Apple();
p.run();
}
}

Output :
it is very good for health

Example of run time polymorphism for animal

class Animal{
void eat(){System.out.println("eating...");}
}
class Tiger extends Animal{
void eat(){System.out.println("eating meat...");}
}
class Pig extends Animal{
void eat(){System.out.println("eating unwasted material...");}
}
class Goat extends Animal{
void eat(){System.out.println("eating grass...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal b;
a=new Tiger();
b.eat();
b=new Pig();
b.eat();
b=new Lion();
b.Goat();
}
}

Output :
eating meat...
eating unwasted material...
eating grass...