Thursday, March 17, 2011

Difference between method overloading and overriding of methods in java

What is the difference between method overriding and method overloading in Java?
 

In: Java Programming [Edit categories]
Tata Job OpeningsTimesJobs.com/TATA_Jobs
TATA Hiring 8000+ for March Register.Apply for TATA Now
Ads
[Improve]
Method overriding is when a child class redefines the same method as a parent class, with the same parameters.
For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.


Overriding is an example of run time polymorphism. The JVM does not know which version of method would be called until the type of reference will be passed to the reference variable. It is also called Dynamic Method Dispatch.

Overloading is an example of compile time polymorphism.

No comments:

Post a Comment