What is Polymorphism

Polymorphism in Java
The process of representing one form in multiple forms is known as Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
Polymorphism is not a programming concept but it is one of the principal of OOPs. For many objects oriented programming language polymorphism principle is common but whose implementations are varying from one objects oriented programming language to another object oriented programming language.
How to achieve Polymorphism in Java ?
In java programming the Polymorphism principal is implemented with method overriding concept of java.
Polymorphism principal is divided into two sub principal they are:
Static or Compile time polymorphism
Dynamic or Runtime polymorphism
Note: Java programming does not support static polymorphism because of its limitations and java always supports dynamic polymorphism.
Following concepts demonstrate different types of polymorphism in java.
Polymorphism means more than one form, same object performing different operations according to the requirement.
Polymorphism can be achieved by using two ways, those are
Method overriding
Method overloading
Method overloading means writing two or more methods in the same class by using same method name, but the passing parameters is different.
Method overriding means we use the method names in the different classes,  that mean parent class method is used in the child class.

To achieve the polymorphism every developer must use the same method names in the project.

1.Method Overloading
2.Method Overriding

1.Method Overloading in Java
If a class have multiple methods by same name but different typses of parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b (int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.
Advantage of method overloading?
Method overloading increases the readability of the program.
Different ways to overload the method

By changing number of arguments
By changing the data type
Example:
 package com.opps;
public class MethodOverLoading {
void add(int a, int b) {
System.out.println(a + b);
}
void add(double a, double b) {
System.out.println(a + b);
}
public static void main(String args[]) {
MethodOverLoading obj = new MethodOverLoading();
obj.add(10.0, 10.0);
obj.add(20, 20);
}
}
output:
20.0
40


Dynamic Binding:
Dynamic binding always says create an object of base class but do not create the object of derived classes. Dynamic binding principal is always used for executing polymorphic applications.
The process of binding appropriate versions (overridden method) of derived classes which are inherited from base class with base class object is known as dynamic binding.
Advantages of dynamic binding along with polymorphism with method overriding are.
Less memory space
Less execution time
More performance
Static polymorphism
The process of binding the overloaded method within object at compile time is known as Static polymorphism due to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded method a memory space is created at compile time when it binds with an object. In C++ environment the above problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so most of the C++ developer in real worlds follows only dynamic polymorphism.
Dynamic polymorphism
In dynamic polymorphism method of the program binds with an object at runtime the advantage of dynamic polymorphism is allocating the memory space for the method (either for overloaded method or for override method) at run time.
Conclusion
The advantage of dynamic polymorphism is effective utilization of the resources, so java always use dynamic polymorphism. Java does not support static polymorphism because of its limitation.
--------------------------------------------------------------------------------------------------------------------------
Method overriding in Java
Method overriding in Java is a concept based on polymorphism OOPS concept which allows programmer to create two methods with same name and method signature on interface and its various implementation and actual method is called at runtime depending upon type of object at runtime. Method overriding allows you to write flexible and extensible code in Java because you can introduce new functionality with minimal code change. Method overriding is different than method overloading in Java which we have discussed in last article. In method overloading, Only name of two overloaded methods are same but method signature must be different while in method overriding, method signature must be same. method overriding represent true polymorphic behaviour, where only name needs to be same underlying method logic can be different. In this Java tutorial we will see What is method overriding in Java, Rules to override method in Java and an example of How to override method in Java.
Rules of method overriding in Java
There are few rules which needs to be followed while overriding any method in Java, failure to follow these rules result in compile time error in Java.
1) First and most important rule regarding method overriding in Java is that you can only override method in sub class. You can not override method in same class.
2) Second important rule of method overriding in Java that name and signature of method must be same in Super class and Sub class or in interface and its implementation.
3) Third rule to override method in Java is that overriding method can not reduce accessibility of overridden method in Java. For example if overridden method is public than overriding method can not be protected, private or package-private; But opposite is true overriding method can increase accessibility of method in Java, i.e. if overridden method is protected than overriding method can be protected or public.
4) Another worth noting rule of method overriding in Java is that overriding  method can not throw checked Exception which is higher in hierarchy than overridden method. Which means if overridden method throws IOException than overriding method can not throw java.lang.Exception in its throws clause because java.lang.Exception comes higher than IOException in Exception hierarchy. This rule doesn't apply to RuntimeException in Java, which is not even need to be declared in throws clause in Java.
5) You can not override privatestatic and final method in Java. private and static method are bonded during compile time using static binding in Java  and doesn't resolve during runtime. overriding final method in Java is compile time error. Though private and static method can be hidden if you declare another method with same and signature in sub class.
6) Overridden method is called using dynamic binding in Java at runtime based upon type of Object. As shown in following example of method overloading.
7) If you are extending abstract class or implementing interface than you need to override all abstract method unless your class is not abstract. abstract method can only be used by using method overriding.
8) Always use @Override annotation while overriding method in Java. Though this is not rule but its one of the best Java coding practice to follow. From Java 6 you can use @Override annotation on method inherited from interface as well.
Method Overloading Example in Java
Now we know what is method overriding in Java and rules of method overriding, It's time to see an example of how to override method in Java. In this example we have used Runnable interface which has an abstract run() method. We have two class Task and PeriodicTask which implements Runnable interface and override run method. For the purpose of demonstrating how method overriding works in Java we are calling run() method in same thread, which you should not, see difference between run and start method to know why. Because run() is overridden in two separate class, call to run() method will be resolved during runtime depending upon type of Object.
 * Java program to demonstrate how to override method in Java.
 * Overridden method are resolved during runtime based upon type of object
public class CollectionTest {

    public static void main(String args[]) {

      Runnable task = new Task();
      task.run(); //call overridden method in Task
 
      task = new PeriodicTask();
      task.run(); //calls overridden method in PeriodicTas

    }


}

class Task implements Runnable{

    @Override
    public void run() {
        System.out.println("Run method overridden in Task class");
    }

}

class PeriodicTask extends Task{

    @Override
    public void run() {
        System.err.println("overridden method run() in PeriodicTask class");
    }
}

Output:
Run method overridden in Task class
overridden method run() in PeriodicTask class


package com.opps;

class RBIBANK {

void depositeMoney() {
System.out.println("IAM  FROM RBI BANK");
}
}

class ICICI extends RBIBANK {
void depositeMoney() {
System.out.println("IAM  FROM ICICI BANK");
}
}

class HDFC extends RBIBANK {
void depositeMoney() {
System.out.println("IAM  FROM HDFC BANK");
}
}
package com.opps;

public class OverrideTest {
public static void main(String[] args)
{
RBIBANK rbi=new RBIBANK();
rbi.depositeMoney();
ICICI icici=new ICICI();
icici.depositeMoney();
HDFC hdfc=new HDFC();
hdfc.depositeMoney();
}


}
    
Output:
IAM  FROM RBI BANK
IAM  FROM ICICI BANK
IAM  FROM HDFC BANK







Share:

No comments:

Post a Comment

Ordered List

Popular Posts

The Magazine

Facebook

Post Top Ad

LightBlog

Post Top Ad

Your Ad Spot

About Me

authorHello, my name is Jack Sparrow. I'm a 50 year old self-employed Pirate from the Caribbean.
Learn More →

Comment

Post Top Ad

Your Ad Spot

Hot

AD BANNER

Sponsor

AD BANNER

Recent Comments

Extra Ads

AD BANNER

Contact Form

Name

Email *

Message *

Translate

Sponsor

test

Home Top Ad

Responsive Ads Here

Flickr

Ad Banner
Responsive Ads Here

About Us

authorHello, my name is Jack Sparrow. I'm a 50 year old self-employed Pirate from the Caribbean.
Learn More →

Recent Posts

Unordered List

  • Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  • Aliquam tincidunt mauris eu risus.
  • Vestibulum auctor dapibus neque.

Sample Text

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation test link ullamco laboris nisi ut aliquip ex ea commodo consequat.

Pages

Theme Support

Need our help to upload or customize this blogger template? Contact me with details about the theme customization you need.