Method Overloading :
- In Java we can define number of methods in a class with the same name.
- Defining two or more methods with the same name in a class is called method overloading.
- Compile determine which method to execute automatically.
- The return type has no effect on the signature of a method.
What is signature of the method ?
- The name of a method along with the types and sequence of the parameters is called signature of the method
- Signature of the method should be unique.
Signature of the method includes -
- No of Parameteres
- Different Parameters
- Sequence of the parameters
Some Examples of the Method Overloading :
int display(int num1,int num2);
Or
int display(double num1,int num2);
Or
void display(double num1,double num2);
Live Example :
package com.pritesh.programs; class Rectangle { double length; double breadth; void area(int length, int width) { int areaOfRectangle = length * width; System.out.println("Area of Rectangle : " + areaOfRectangle); } void area(double length, double width) { double areaOfRectangle = length * width; System.out.println("Area of Rectangle : " + areaOfRectangle); } } class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(); r1.area(10, 20); r1.area(10.50, 20.50); } }
Explanation :
- We have defined 3 methods with same name and different type of parameters.
- When both integer parameters are supplied to the method then it will execute method with all integer parameters and if we supply both floating point numbers as parameter then method with floating numbers will be executed.
The post Method Overloading in Java Programming appeared first on Learn Java Programming.