Method Overriding and Overloading in Java
What is the difference between overriding and overloading a method in Java? What are these things used for?
Method overloading is providing two or more separate methods in a class with the same name but different parameters, e.g. a different method signature. The method return type may or may not be different, so we can reuse the method name.
The main reasons to use method overloading are to reduce duplicated code and not have to remember multiple method names.
As a quick example, here is a Person class. What if we want to enable a person to walk, but also want to be able to have them walk a specified number of steps? Instead of making a new method like walkSteps(int steps)
, we can reuse the method name and put in a steps parameter, enabling the walk method to be used with or without a parameter.
Method overloading is generally used within a class and requires a parameter to be changed.
Method overriding is when a method defined in a child class already exists in the parent class with the same method signature. In the child class, the @Overrride
annotation is used above the method signature to alert the compiler to use this method, not the parent method.
For example, say we have a Person class who can walk, and Bob who is a child class to Person and can also walk. To customize Bob’s walk method, we just add the annotation and add the custom implementation.
Method overriding is used to give a custom implementation of a method already provided in the parent class. If needed, the parent method can be accessed by using super.methodName()
. When overriding, the child method must use the same parameters as the parent method.