Saturday, November 26, 2016

method overloading in java - Polymophism

     WE Define Polymorphism?

In general term polymorphism is combination of two word one is poly which mean many and second is morphs which means forms. So, polymorphism means many forms. Now in programming polymorphism means doing single task with different ways, polymorphism increase the code readability. Polymorphism is also called Dynamic method dispatch.

There are two methods in java which perform polymorphism which are the following:
o   Method overloading
o   Method overridden

There are two types polymorphism in java
o   Compile time polymorphism
o   Run time polymorphism

Method overloading:

The methods with same name but different number of parameters or different datatypes are known as method overloading. Method overloading is used to achieve compile time polymorphism. Method overloading is used to increase the readability of the program

Example of Method overloading with different no of parameters



different parameters


Example of Method overloading with different data types

overloading different data types


 Method overridden

When a sub-class (child class) having the same method with same parameter in supper-class (parent class) is known as method overridden. Method overridden is used to achieve rum time polymorphism. To create a method overridden you have to care of the following things
o   Method overridden has same name as a parent class method name
o   Method overridden as same parameters as a parent class method parameter
o   The class of method overridden must be a “IS-A” relationship (Inheritance)

Example

Method overridden

Now above program the sub class Horse and Loin having the same method of the parent class Animal. Now the concept is every animal eating something so I take two animals Horse and Loin. Horse and Loin both are the child of Animal, so they both having overridden method. So, sub classes implement that this overridden method according to their nature. This is the use of overridden method.

In polymorphism there is another important concept which is up-casting. Up-casting is a process in which the reference variable of the parent class refers the child class object. By the use of up-casting we can get multi-level inheritance. Up casting is also used to achieve generalization

Example

methodOverride

         Down casting
The process in which reference of child class refers the object of parent class is known as down casting. It is reverse process of up-casting. Like up-casting the down-casting is not being done easily we have to explicitly force to perform down casting. Down casting is also used to access specialization.

Example:        
                 parent class Animal and child classes Horse which extends the Animal class now for down casting we have to write the object in this way
                Animal a;
                Horse h = (Horse)   a; // this is the down casting object





No comments:

Post a Comment