Polymorphism in Java

Polymorphism made of two words poly means many and morph means forms. so we can say that the ability to have more than form is called as polymorphism.

Polymorphism is the OOPs concept, and in Java, it can be implemented using method overloading.

Example:

here is the example of polymorphism

class Person
{
     void walk()
     {
     System.out.println("Person can Run....");
     }
}
class Athlete extends Person
{
     void walk()
     {
     System.out.println("Athlete can Run Fast...");
     }
     public static void main(String arg[])
     {
     Person p=new Athlete(); //upcasting
     p.walk();
}
}

We created two class, Person and Athlete. Athlete class extends Person class feature and override walk() method. We are calling the walk() method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Here method invocation is determined by the JVM and not compiler. So, it is known as runtime polymorphism.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: