Skip to main content

Method Overloading in Java | Type Promotion | Ambiguous Problem | Var args in Method Overloading

 

Method overloading in java

What is Method Overloading?

Method Overloading means one class have same methods name but have different parameters or arguments.

In simple term, when any class contains same method name in class but with different parameters it is called Method Overloading in Java.

In another simple term, using Method overloading in java we can create multiple same name methods in one class.

In Method Overloading, method resolution always takes care by compiler based on method parameters. So it is also called Compile Time Polymorphism or Static Polymorphism or Early Binding.

Learn more about Polymorphism and OOPs concept :

In Method Overloading, method signature must be different. Means if we write same method signature in same class it gives compile time error.

What is Method Signature?

In java, method signature contains only method name followed by argument types. following code is called method signature in java. 

Note : In java, return type is not included as method signature.

methodName(int param1, int param2) 

Follow simple code of Method Overloading :

Example 1 : Simple code for Method Overloading

public class MethodOverloading {

    public void overloadingMethod() {
    }
    
    public void overloadingMethod(int parameter) {
    }
    
    public void overloadingMethod(double parameter) {
    }
    
    public void overloadingMethod(int parameter1, double parameter2) {
    }
    
    public void overloadingMethod(double parameter1, int parameter2) {
    }

}

You can see we defined 5 methods with same name but argument type is different. In above code we can also take different return type than void.

Compiler use method signature while method calls.

Lets see real time example of Method Overloading so you better understand where we have to use.

Example 2 : Method Overloading real time example

class Student {
    int id;
    String name;
    int std;
    double percentage;
}

public class MethodOverloading {

    public Student getStudent(int id) {
        // Logic
        return student;
    }
    
    public List<Student> getStudent(String name) {
        // Logic
        return studentList;
    }
    
    public List<Student> getStudent(int std) {
        // Logic
        return studentList;
    }
    
    public List<Student> getStudent(int std, double percentage) {
        // Logic
        return studentList;
    }

}

What is benefits or advantages of Method Overloading in Java?

  • Method Overloading reduces complexity. because we does not have to remember many methods.
  • Overloaded methods give programmers the flexibility to call a similar method for different types of data.
  • It is used to perform a task effectively with smartness in programming.
  • It provides cleaner and readable code.

Lets see simple example of Method Overloading.

Example 3 : Example of Method Overloading

public class MethodOverloading {

    public void overloadingMethod() {
        System.out.println("Non Argument");
    }
    
    public void overloadingMethod(int parameter) {
        System.out.println("Int Argument : "+parameter);
    }
    
    public void overloadingMethod(double parameter) {
        System.out.println("Double Argument : "+parameter);
    }
    
    public void overloadingMethod(int parameter1, double parameter2) {
        System.out.println("Sum of Two Arguments : "+(parameter1 + parameter2));
    }
    
    public static void main(String args[]) {
        MethodOverloading obj = new MethodOverloading();
        obj.overloadingMethod();
        obj.overloadingMethod(10);
        obj.overloadingMethod(10.0);
        obj.overloadingMethod(10, 20);
    }
}

Output :

Non Argument
Int Argument : 10
Double Argument : 10.0
Sum of Two Arguments : 30.0

You can see when we pass integer value then it is called method whose parameter is int. and it is decide by compiler at compile time.

What if someone pass different arguments in method and it is not available in class?

What is Automatic Type Promotion in Method Overloading?

If compiler does not find exact parameter method then it does not directly gives compile time error, first it promote argument type to next level. like,

char -> int -> long -> float -> double

If we pass char parameter in method and class does not contains any method who is taking char parameter, then compiler automatic promote argument to next level means char to int, if int parameter also not found it goes to next level long.

At last, if compiler does not find promoted method or promotion is not possible then it gives Compiler Time Error. 

If you are using any IDE like eclipse, it will show error suggestion if any promotion method is not found.

Automatic Type Promotion in Method Overloading.

Above concept is called Automatic Type Promotion in Method Overloading.

See following example for type promotion :

Example 4 : Type promotion in Method Overloading

public class MethodOverloading {

    public void overloadingMethod(int parameter) {
        System.out.println("Int Argument : "+parameter);
    }
    
    public void overloadingMethod(float parameter) {
        System.out.println("Double Argument : "+parameter);
    }
    
    
    public static void main(String args[]) {
        MethodOverloading obj = new MethodOverloading();
        obj.overloadingMethod('a');
    }
}

Output :

Int Argument : 97

What happened when Two or more method is applicable for Type Promotion?

If parent and child, both method type matched then, child gets highest priority than parent. 

See below example for more clarity.

Example 5 : Method overloading parent child type priority

public class MethodOverloading {

    public void overloadingMethod(Object parameter) {
        System.out.println("Object Argument : "+parameter);
    }
    
    public void overloadingMethod(String parameter) {
        System.out.println("String Argument : "+parameter);
    }
    
    
    public static void main(String args[]) {
        MethodOverloading obj = new MethodOverloading();
        obj.overloadingMethod(null );
    }
}

Output :

String Argument : null

In above example, we have only two method with Object and String type. So output is become String Argument because String is child class of Object class.

What is ambiguous problem in Method Overloading? or Why ambiguity problem occurs in  Method Overloading?

If more than one member method is both accessible and applicable to a method invocation the Java programming language uses the rule that the most specific method is chosen. So here java compiler doesn’t consider any of them to be more specific, hence we get ambiguous error.

In simple term, when two or more match found for same type parameter, then compiler throws ambiguous method error. See below example.

Example 6 : Ambiguous method error in Method overloading

public class MethodOverloading {

    public void overloadingMethod(float args1, int args2) {
        System.out.println("float and int method");
    }

    public void overloadingMethod(int args1, float args2) {
        System.out.println("int and float method");
    }
    
    public static void main(String args[]) {
        MethodOverloading obj = new MethodOverloading();
        obj.overloadingMethod(1, 1);
    }
}

Output :

 Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The method overloadingMethod(float, int) is ambiguous for the type MethodOverloading

Variable arguments (Varargs) vs Simple args in Method Overloading.

When in method overloading, both general and varargs method matched for type, then always general method get first priority.

Varargs method always gets least priority. Because Var-args were added late in Java API. lets see example for better understanding.  

Example 7 : Var-args vs simple args

public class MethodOverloading {
    
    public void overloadingMethod(int args) {
        System.out.println("int argument");
    }
    
    public void overloadingMethod(int ...args) {
        System.out.println("Var args argument");
    }
    
    
    public static void main(String args[]) {
        MethodOverloading obj = new MethodOverloading();
        obj.overloadingMethod(1);
        obj.overloadingMethod();
    }
}

Output :

int argument
Var args argument

 

Other articles :



Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...