Method Overloading and Method Overriding in Java
What is Method Overloading?
Java is an object oriented programming that why it inherit all properties of OOP, here we will discuss about what is method overloading in Java with example. Basically when we have multiple methods with same name but different perimeters is called method overloading.
Let suppose we have a method named add(int x, int y) in class Mathematics, we have another method with same name add(int x, int y, int z) but carrying three integer value as perimeters. We also have another class TestMathematics with main method where we can call both methods of Mathematics class to test them with different perimeters.
- class Mathematics{
- static int add(int x, int y){return x+y;}
- static int add(int x, int y ,int z){return x+y+z;}
- }
- class TestMathematics{
- public static void main(String[] args){
- System.out.println(Adder.add(15,10));
- System.out.println(Adder.add(15,20,10));
- }}
Output is:
25 45
Advantages of overloading?
Overloading in Java is the ability to create multiple methods of the same name, but with different parameters.
The main advantage of overloading is cleanliness of code.
It increases the readability of the program.
Overloaded methods provide programmers the flexibility to call a similar method for different types of data.
It is also used on constructors to create new objects given different amounts of data.
You must define a return type for each overloaded method. Methods can have different return types
What is Method Overriding?
Method overriding is another strong concept of OOP, Here we override method with same name and perimeters. For method overloading we must have at least two classes (Parent & Child class). Let suppose we have a Vehicle (parent class) with run() method, we have another child class Rav4 extend from Vehicle class, and also have a run() method same as parent class.
Lets look at the Java code.
Output is:
Rav4 is running safely
Advantage of method overriding
The main benefit of method overriding is that the class can give its own detailed implementation to an inherited method without even changing the parent class code.
This is cooperative when a class has some child classes, so if a child class wants to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code.
Difference between overloading and overriding
|
|
1. it occur within one class 2. name of the method will be same but different parameter. 3. Return type can be same or different. 4.It is an example of compile time polymorphism |
1. occurs in at least two classes, one parent and the other child class. 2. Name and Parameter both will be same.3. Return Type is always same 4. it is an example of runtime polymorphism |
0 Comments