This question already has an answer here:
- Java overloading and overriding 7 answers
- Java overloading and overriding 8 answers
What is the difference between overloading a method and overriding a method? Can anyone explain it with an example?
This question already has an answer here:
What is the difference between overloading a method and overriding a method? Can anyone explain it with an example?
Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.
Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The
@Override
annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.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
extendsjava.util.HashSet
. The methodadd()
is overridden inLinkedHashSet
. If you have a variable that is of typeHashSet
, and you call itsadd()
method, it will call the appropriate implementation ofadd()
, based on whether it is aHashSet
or aLinkedHashSet
. 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.