Overloading vs Overriding in Java

03/10/2009

Overloading and overriding are completely different. Only the notion about interface (function) name is same. Overloading is the ability to use same interface name but with different arguments. Purpose of functions might be same but the way they work will differ based on the argument types. Overriding is applicable in the context of inheritance. When there is a need to change the behavior of a particular inherited method, it will be overridden in the sub-class.

Overloading itself is not polymorphism and similarly run-time binding itself is not polymorphism. All these and more are used to exercise the object oriented property polymorphism.

Ads by Google

Overloading and Overriding Key Points

  • private: A java private method cannot be overridden because, it is not accessible to an inheriting class.
  • final: Method overloading a Java final method is possible but overriding a final method is not allowed.
  • final: Two methods with same parameters list and in one method we have parameters ‘final’, in this case two methods are not different methods and overloading is not possible.
  • static: Method overloading a Java static method is possible but overriding a static method is not possible.
  • static: Overriding is in the context of objects (instances) and inheritance. A method declared as static belongs to the whole class (common for all objects). So there is no point of overriding it in sub-class.
  • static: In overloading if two methods are different only by a static modifier then its not possible to overload. The arguments list must be different.

Overloading

Let’s discuss overloading in detail. In websites, I generally see a overloaded truck as example for overloading. It symbolizes that, adding more attributes, methods to a class and making it look bulkier is overloading. Please get it right, in fact when we use overloading for the outsiders view the class will look compact.

Before Overloading

I have shown two images, first one is called Harmonium. Its a classical music instrument from India and its a primitive version of piano. The other is a modern digital keyboard. In our overloading context, Harmonium is before overloading and keyboard is after overloading.

After Overloading

This is an attempt to closely mimic overloading :-)

Java Example for Method Overloading


public class OverloadExample {
	
	public static void main(String args[]) {
		System.out.println(playMusic("C sharp","D sharp"));
		System.out.println(playMusic("C","D flat","E flat"));
	}

	public static String playMusic(String c, String d) {
		return c+d;
	}
	public static String playMusic(String c, String d, String e){
		return c+d+e;
	}
}

Java Overloading Puzzle

package com.javapapers.java;

public class NullArgumentOverloading {

	public static void main(String[] args) {

		NullArgumentOverloading obj = new NullArgumentOverloading();
		obj.overLoad(null);
	}

	private void overLoad(Object o) {
		System.out.println("Object o argument method.");
	}

	private void overLoad(double[] dArray) {
		System.out.println("double array argument method.");
	}

}

Can you guess the output?

Overriding

When a class is inherited we get the base class’ methods and attributes based on the respective access modifiers. A specific inherited method’s behavior may not be suitable in the sub-class. So we replace the inherited method’s behavior as required. After overriding, the old behavior is completely obsolete.

Look at this monster truck, the old small four wheels are replaced with huge wheels to suit the need. This is overriding in real world.

Overriding

Overriding in Java / JDK

Implicitly every object in Java is extended from Object class. Object has a method named equals. In String class the default behavior is overridden.  The String equals behavior is modified to check if the character sequence is same as the compared one and returns true.

This Core Java tutorial was posted on 03/10/2009.
Ads by Google

175 comments on “Overloading vs Overriding in Java

  1. Nice comprehensive information sir….Thanks.

  2. Nice example to understand the concepts easily Thanks

  3. Nicest example that I have ever seen or think of for these blury concepts “overloading” and “overriding” in my 12 years exposure to java. Your simple way of explaining is superb! Hearty thanks & wishes!!

  4. very very thank u sir …very nice explanation sir

  5. thanks a lot for explanation.. only now I understand clearly the difference between overloading and overriding

  6. This information is superb.Thanx alot.I understand this topic very easily by those examples. the summary of key points on how Java implements overloading and overriding is superb. Thanq

  7. Nice Observation on how Java does overriding. Thanks.

  8. thnx sir it is helpful for understanding overloading and overriding.
    thanks

  9. Nicest example to explain the two confusing concepts of OOPS.

    thank u sir

  10. overriding is explained well, overloading concept is also good but the use of word “interface” is quite confusing….

    • Here in this context, I have used the word interface to express a Java method signature. Surely this is not Java interface class.

  11. (it is Just Good For Beginers)..
    And…. It is not Sufficient…for advanced experts. overloading puzzle is good.
    Give Two three Programatical Examples…

  12. Can you give a code example for over riding like over loading….?

  13. Overloading simplest example

    public class OverLoad
    {
    void sum(int x, int y)
    {
    int sum=x+y;
    System.out.println(“sum is: “+sum);
    }
    void sum(int x, int y, int z)
    {
    int sum=x+y+z;
    System.out.println(“sum is: “+sum);
    }
    public static void main(String arg[])
    {
    OverLoad ol=new OverLoad();
    ol.sum(5,4);
    ol.sum(5,4,3);
    }
    }

    o/p-> sum is: 9
    sum is: 12

    Overriding simplest example

    class A
    {
    void calculate(int x, int y)
    {
    int sum=x+y;
    System.out.println(“sum is: “+sum);
    }
    }
    public class B extends A
    {
    void calculate(int x, int y)
    {
    int product=x*y;
    System.out.println(“product is: “+product);
    }
    public static void main(String arg[])
    {
    B b=new B();
    b.calculate(5,4);
    }
    }

    Run this code o/p will be 20

    class A
    {
    void calculate(int x, int y)
    {
    int sum=x+y;
    System.out.println(“sum is: “+sum);
    }
    }
    public class B extends A
    {
    /*void calculate(int x, int y)
    {
    int product=x*y;
    System.out.println(“product is: “+product);
    }*/
    public static void main(String arg[])
    {
    B b=new B();
    b.calculate(5,4);
    }
    }

    run this code o/p will be 9

    now i think u are clear… if still not. leave the comment

  14. Great!!!.nice real world eg. to explain the core concept.

  15. your concept is very clear please send me some concept and example in my email related to applet,exception ,thread… Thanks

  16. Joseph , I could not digest “Run time binding is not polymorphism”.But I believe it is otherwise. Overloading is static binding since at compile time it is bind,And also overloading is not polymorphism”, whereas overriding is polymorphism since it is binded at runtime.

    Clear the confusion

    • I am expressing that those words cannot be used interchangeably. When we say polymorphism, it is a whole larger concept comprising of all these things.

  17. overloadin=it is the relation biw the method declare in supper class and subclass having thr same method name name diffirent no input and diffirent type of input–;;; for eg
    public void m1()// no argument constructer
    public void m1(int i)// argumenter contructer
    public void m1(inti,String s)// this is all about the method overloading

  18. Nice Explanation for Overriding. The truck example for overriding is cool.

  19. Dear Joseph, this is the very simple and easy to understand article.so we are thank to you………………

  20. If example is given for overriding then it would be possible to understand more clearly….

  21. Is it true that Overloading is not a polymorphism?

  22. this overloading and overriding concept is very clearly explained,and before reading this topic i didn’t understand these two task difference,now am understand completely. thank to you

  23. All your answers are awesome relating to realtime easy understanding thank you for sharing your knowlegde. can you please explain java polymorphism it hasnt been very clear to me all time although partially i understand still not clear.

    thanks
    raj

  24. Nice fundamental introduction on overloading and overriding. A deep analysis would be appreciated.

  25. Hi,

    In one of the interview I got this question:

    Consider this example:

    class P {

    public void abc() {

    }

    Now class C inherits class P

    class C extends class P{

    public void abc() {

    // adds some additional functionality;

    }
    Now, here is the question:
    Due to some reasons if you want the functionality of abc method of class P (i.e parents )in child’s class, then how we can achieve this?. Is it through key word super?

    I understand this is very strange, but it was asked in interview

    Thank u,

    • simply create an object to child class and call the super class method

  26. Give an example when you can not overload a method in Java.

  27. wow simply super…..great explanation .thank u

  28. hi its really useful 4 me to understand tanqu…

  29. Consider this example:

    class P {

    public void abc() {

    }

    Now class C inherits class P

    class C extends class P{

    public void abc() {

    // adds some additional functionality;

    }
    Now, here is the question:
    Due to some reasons if you want the functionality of abc method of class P (i.e parents )in child’s class, then how we can achieve this?. Is it through key word super?

    I did not understand the question here..
    Can’t we do like this –

    P sup = new P();
    P sub = new C();
    sup.abc(); //Calls super class method
    sub.abc(); //Calls sub class method

    Please let me know if its not correct..

    Thanks,
    Deepesh

  30. Thanks Sir, its very nice and very easy to understand that.

  31. thnx sir it is helpful for understanding all concepts. Iam a beginner,I want to download all your core concepts for java, How Can i download, please send to my mail.

    Thanxs a lot, great job!!!

  32. can u override the static method?many of people asking this question.
    YES OR NO
    IF YES GIVE AN SUITABLE EXAMPLE WITH EXPLANATION.

  33. PLEASE HELP ME IN ABOVE QUESTION…

  34. AOA
    Very Informative Post & Blog – Keep doing Sir :)

    Best Regards;

  35. i want more clarification plz give more without confusion

  36. can the main function be overloaded??
    (public void static main(String []args))

    • Yes it can be overloaded and no issues. But, the method with single String-array argument will be invoked as always.

  37. this is the very simple and easy to understand article.so we are thank to you………………

  38. Pingback: Decorator Design Pattern

  39. Thanks for explaining in a simple language.

  40. hi jo..thank you so much…its very useful website…

    Karunakar

  41. There are times when your article is complete and one requries no more reading.

    this is NOT one of them. Please try to put some examples and rules/protocol associated.
    eg: you didnt explain the access modifiers / scope in over-riding
    eg: return type in overloading

    gud effort nevertheless…

  42. Never read a better article elsewhere. Simple description and I will never forget overloading and overriding hereafter.

  43. excellent !
    can u give some more example in c++

    Shilpi

  44. Amazing way of drilling the concept of Overloading and Overriding into the head.

    Thanks Joe

  45. can return type differ in overloading and overriding?

  46. nice explanation but little bit confusion can u please explain it clearly…….

  47. very nice example with real world…:)

  48. Thank you sir :) i got to know the concept

  49. i really thanks to you very much ……i understood both overloading and overriding concept very well.

  50. thnks sir nyc explaination………..

  51. thank u sir

    loving example and awlanationesome exp

  52. Nitin given this example to explain overriding but i have a doubt in this below example that is “What is the use of extending A class in B?” without extending that class also we will get the same result na…

    Overriding simplest example

    class A
    {
    void calculate(int x, int y)
    {
    int sum=x+y;
    System.out.println(“sum is: “+sum);
    }
    }
    public class B extends A
    {
    void calculate(int x, int y)
    {
    int product=x*y;
    System.out.println(“product is: “+product);
    }
    public static void main(String arg[])
    {
    B b=new B();
    b.calculate(5,4);
    }
    }

    Run this code o/p will be 20

  53. Overriding simplest example

    class A
    {
    void calculate(int x, int y)
    {
    int sum=x+y;
    System.out.println(“sum is: “+sum);
    }
    }
    public class B extends A
    {
    void calculate(int x, int y)
    {
    int product=x*y;
    System.out.println(“product is: “+product);
    }
    public static void main(String arg[])
    {
    B b=new B();
    b.calculate(5,4);
    }
    }

    Run this code o/p will be 20

  54. Superb its very useful thing which u have explained in detail with a very gud examples …Thanks a lot

  55. I like your way of explanation.
    Its good and easy to understand.

  56. hi joe i have seen couple of your articles which were very intereseting and simple … thanks for sharing your knowledge.

  57. very nice article
    There is any concept of consructor overriding?

  58. very nice explanation sir….
    u have explained it very well….

  59. thanks for giving a clear view in real time application….

  60. Nitin given this example to explain overriding but i(raju) have a doubt in this below example that is “What is the use of extending A class in B?” without extending that class also we will get the same result na… (raju……)

    Overriding simplest example

    class A
    {
    void calculate(int x, int y)
    {
    int sum=x+y;
    System.out.println(“sum is: “+sum);
    }
    }
    public class B extends A
    {
    void calculate(int x, int y)
    {
    int product=x*y;
    System.out.println(“product is: “+product);
    }
    public static void main(String arg[])
    {
    B b=new B();
    b.calculate(5,4);
    }
    }

    Run this code o/p will be 20

    Raju on April 26th, 2012 10:53 pm
    ——————————–
    Raju, without extending class A also possible, but if u want to access method(s) in class A, u need to create object for class A seperately.
    If we write class B extends A
    there is no need of creating objects for both classes. simply we can create object for class B and also access method(s) in class A also. That is behaviour of inheritence.
    class to class – extends
    interface to interface – extends
    class to interface- implements

  61. good explanations… it helps to learn easily. thank you to everyone.

  62. hii,
    these concepts r too easy to understand

  63. ok sir, i understood your concept but i want
    to get run time input with super key word code with explanation.

  64. thnx i understand this very easily………

  65. Awesome……Example given on overriding is been fantastic!!

  66. Thanks for the explination dude.. It helped me a lot.. :-)

  67. Thank you very much…………
    for the simple & understood…….
    hum……………
    nice………….

  68. I like your way of explanation.
    Its good and easy to understand.thank uuuuuu

  69. Pingback: Why Multiple Inheritance is Not Supported in Java

  70. hai sir this is good i able to understood this and thank u so much

  71. An Excellent explanation and helps a lot to the person who is new to java….very good explanation to all the articles…I am following the posts regularly….Thank you so much….

  72. Excellent explanation thank you sir.and i have one doubt what is static overloading and dynamic overloading .give me one example

  73. best comparison i have evry found on net is this one….. cleared all my doubts. thx for this. (first time in my life i am writting a comment on some blog in last 7 years)

  74. great explanation.. Helped me understand the terms better. Thank u..

  75. I clear my concept about overriding & overloading but I want practical example on both where I can programiticaly use it.

  76. Very good example about both.

    Thanks

    Raj Chaudhary

  77. Statement : Derived classes still can override the overloaded methods. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.

    Can anyone help me understand this statement?

  78. the method is good for the st udents but to put briefly in the libriry system.

  79. nice article liked it very much.thanks

  80. hi,

    joe am a bigneer i need your help please let me know were do i get good understandable programs to practice and simultaneously complete java topics to learn.reply me as soon mas possible urgent……………………….

  81. the above way is good. but you have to tell some points wise then easly understand…..

  82. nice work sir….ur notes are very good n easy to understand thanx a lot

  83. Pingback: Android SQLite Database

  84. the best example i’ve seen… thanks a lot sir.

  85. its very interesting and easy to understand…Thanks a lot…

  86. Pingback: System.out.println

  87. very very very niceee………………

  88. Pingback: Java Clone, Shallow Copy and Deep Copy

  89. The example of harmonium and piano has explained the term Overloading in awesome way…
    Cant forget this term ever in my life from now…

  90. the example explained is awesome, cant ever forget this term in my life.

  91. i have one question regarding overloading, can we achieve overloading in case of inheritance.

    As explained in below example is overloading is achieved in class B.

    class A
    {
    public void test(int i)
    {
    System.out.println(“From class A test method”);
    }

    }

    class B extends A
    {

    public void test(int i,int j)

    {
    System.out.println(“From class B method”);

    }

    public static void main(String args[])
    {

    }

    }

  92. Pingback: Excel Export in Spring MVC

  93. Pingback: Java Polymorphism

  94. Colors also contribute to total beauty of your garden. s
    behavioral problem. I put a smal amount of wateer in a plastic cup
    and quietly stood in front off my dog, without saying a word.

  95. in the puzzle given in your tutorial, obj.overload(null) is calling double array method. wanted to know why the object o method is not called? because even object o can be null.

  96. Hi Joe,

    Thanks for the information because There will be always confusion about the overriding and overloading. It is good that you have explained well.

    Thanks,

  97. hi joe,
    it would be better if you use a good example than this.

  98. Brother super explanation hats off bro.

  99. Hi Joe,

    Could you please explain why “double array argument method” is called in the puzzle? Thanks in advance.

  100. Pingback: Covariant Return Type in Java

  101. DEAR SIR
    I HAVE A DOUBT. EVERY TEACHER CALL METHOD OVERLOADING IS A STATIC POLYMORPHISM.BUT SIR EVERY METHOD IS BINDED WITH THE OBJECT AT THE RUN TIME.BCZ OBJECT CREATED AT RUN TIME .THEN HOW IT STATIC

  102. DEAR SIR
    I HAVE A DOUBT. EVERY TEACHER CALL METHOD OVERLOADING IS A STATIC POLYMORPHISM.BUT SIR EVERY METHOD IS BINDED WITH THE OBJECT AT THE RUN TIME.BCZ OBJECT CREATED AT RUN TIME .THEN HOW IT STATIC

Leave a Reply

Your email address will not be published.

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>