Overloading means having two methods in the same class with the same name but different parameters or whereas Overriding occurs when parent class and child class have a method with same name and parameters.
Overloading means having two methods in the same class with the same name but different parameters or whereas Overriding occurs when parent class and child class have a method with same name and parameters.
The main importance of overriding is that it allows child class to have its own implementation of a method found in the parent class.
Source: Defining Methods
The main importance of overriding is that it allows child class to have its own implementation of a method found in the parent class.
Overloading Vs Overriding
- Overloading happens at compile-time wheres Overriding happens at run-time.
- Polymorphism does not apply in Overloading, only in overriding.
Example of Overriding
/** * * @author Eric * www.techoverload.net */ public class Birds { void haveWings() { System.out.println("All birds have Wings. "); } } //Inner Class Penguins class Penguins extends Birds { //Overriding method haveWings which has been declare in parent class void haveWings() { System.out.println("Penguins have wings to enable them " + "move in water easily."); } public static void main(String args[]) { new Penguins().haveWings();//Create a new Object Penguins and calling haveWings method. } }
Explanation
Above class Penguins Inherits haveWings() method from its superclass or parent class.Penguins class goes ahead to do its own implementation on this method.Read more about Inheritance
Example of Overloading
/** * * @author Eric * www.techoverload.net */ public class SumNumbers { static void calculateTotal(int a,int b,int c) { int total=a+b+c; System.out.println("Total is " +total); } static void calculateTotal(int a,int b) { int total=a+b; System.out.println("Total is " +total); } public static void main(String args []) { calculateTotal(123,23,67); calculateTotal(98,34); } }
Quick Lessons to learn from this Tutorial.
Here are some of the lessons you can learn from above code.
1.There are two ways of overloading methods.These are
Changing the number of parameters.
Changing Data types of parameters.
2.A non-static method cannot be referenced inside a static context.
That the reason why calculateTotal method is static.
3.When calling a static method you don't have to create a class object.
That why we have not create SumNumbers object.
Above overloading, examples use numbers of parameters as the way to overload calculateTotal method.
Source: Defining Methods