What is Method Overloading in Java ?

Java is Object Oriented Programming Language, means it contains classes and objects.
A class in java contains methods and properties. A class with multiple methods with same and different arguments is called Method overloading.
 These arguments can be defined in different ways.

  • No of parameters
  • Data type of parameters
  • Sequence of parameters

void print(int i){
    System.out.println(i);
}
void print(double d){
    System.out.println(d);
}
void print(char c){
    System.out.println(c);
}

Method Overloading in Java is Static Polymorphism
Calls to overloaded methods will be resolved during compile time, In other words, when the overloaded methods are invoked, JVM will choose the appropriate method based on the arguments used for invocation. 

 

void add (int a, int b)
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)

 

Methods differing only in return type
Methods differing only in return type will not be treated as overloaded methods, it will be compilation error. For Example, the below given methods will give compilation error

void print(int k){
    System.out.println(k);
}
int print(int k)){
    System.out.println(k);
    return k;
}

 

Overloading the Constructors

public class Teacher{
    public Teacher(){
        mark = 100;
    }
    public Teacher(int rollNo, double mark){
        this.rollNo = rollNo;
        this.mark = mark;
    }
}