Core Java Tutorial

Core Java Tutorial

Method Overloading in Java

Method Overloading

Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures.Overloading is also known as Compile time polymorphism.

Example:
public class Student {

 String name;

 int age;

 String email;

 public void setData(String name, int age)

 {

  this.name = name;

  this.age = age;

 }

 public void setData(String name, int age, String email)

 {

  this.name = name;

  this.age = age;

  this.email = email;

 }

 public void display()

 {

  System.out.println(name);

  System.out.println(age);

  System.out.println(email);

 }

 public static void main(String[] args) {

  Student s1 = new Student();

  s1.setData("Shanthi", 20);

  Student s2 = new Student();

  s1.setData("Veera", 25, "[email protected]");

 }

}

Rules for overloading

  • Overloading can appear in the same class or a subclass.

  • Overloaded methods MUST change its number of argument or its type.

  • When declaring two or more methods in same name complier differentiate them by its arguments, so you cannot declare two methods with the same signature.

  • Overloaded methods CAN have different return type.

  • The compiler does not consider return type when differentiating methods, so it’s legal to change return type of overloaded method.

  • Overloaded methods CAN change the access modifier.

  • Similarly overloaded method can have different access modifiers also.

  • Overloaded methods CAN declare new or broader checked exceptions.

Legal overloading

Overloaded method should have different argument.

public class Student {

 public void add(int i, int j)

 {

 }

 public void add(int i)

 {

 }

}

It’s legal for Overloaded method to change only its type.

public class Student {

 public void add(int i)

 {

 }

 public void add(float i)

 {

 }

}

Overloaded method can change its return type.

public class Student {

 public void add(float i)

 {

 }

 public int add(long i)

 {

  return 0;

 }

}

Overloaded method can have different access modifiers.

public class Student {
 public int add(long i) {
  return 0;
 }
 private void add(char c) {}
}

Overloaded method can declare new or checked exception.

public class Student {
 public void add(int i) {
     
 }

 public void add(short s) throws Exception {}
}

Illegal overloading

You cannot overload a method by changing only its return type.

public class Student {
 public void add(int i, int j) {
}
 public int add(int i, int j) // Compilation error - method already defined
 {
}
}