Method overriding and overloading in Java

I know this may be trivial for many people but then it can be pretty confusing for new bees (pssst.. in the beginning me too used to be confused between overloading and overriding)

OVERRIDING – when you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overriding.

Example:

public class BaseClass{

public void methodToOverride()

{

//Some code here

}

}

public class DerivedClass extends BaseClass{

public void methodToOverride()

{

//Some new code here

}

}

As you can see, in the class DerivedClass, we have overridden the method present in the BaseClass with a completely new piece of code in the DerivedClass.

What that effectively means is that if you create an object of DerivedClass and call the methodToOverride() method, the code in the derivedClass will be executed. If you hadn’t overridden the method in the DerivedClass then the method in the BaseClass would have been called.

OVERLOADING -  when you have more than one method with the same name but different arguments, the methods are said to be overloaded.

Example:

public class OverLoadingExample{

public void add(int i, int j)

{

int k = i + j;

}

public void add(String s, String t)

{

int k = Integer.parseInt(s) + Integer.parseInt(t);

}

}

As you can see in the example above, we have the same method add() taking two parameters but with different data types. Due to overloading we can now call the add method by either passing it a String or int :)

Tags: ,

78 comments

  1. Perfect answer for the beginners…
    Thank you!!! :)

  2. Thanks u so much

  3. thank for post the confusion free example.
    thanks a lot!!!!!!!

  4. thnx for ans it helped to clear my basics for xams…

  5. Good explanation…..
    thanx.!

  6. thanku so muchh…

  7. accurate answer no ambiguity remains after reading this

  8. very clear explanation

  9. Thanks for the Clarification….

  10. best example….thanks

  11. thanq :)

  12. soundarya kumari

    vgood

  13. really nice example in easy language , easy to understand
    thanks

  14. Thank u for understandable explanation

  15. thank u

  16. thanks a lot!!!

  17. Good Example but What is the use of this? and when will we use this Conditions

  18. but What is the use of this? and when will we use this Conditions

  19. short and clear answer thank you…………..

  20. wow great…….short and clear examples…

  21. thank you

  22. Good but not excellent, always try for excellent

  23. Good explanation , thanks alot.

  24. very short and clear ,thank you

  25. Exact answer for the beginners.Thankyou

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>