'What is overloading in Java?

I don't understand the overloading in Java. Is there a relation with polymorphism ? It seems very abstract for me. I come more from Javascript language ? Would this apply so in Javascript ?



Solution 1:[1]

Overloading is feature that allows having 2 methods with the same name and different signature in one class, e.g.

public void foo();
public void foo(int i);

Now you can call method foo() without arguments or with one int argument and different methods will be executed.

You are probably confused with overloading and overriding. Overriding indeed relate to polimorphysm. This is ability to overrride (change) functionality of base class into subclass. For example if Child extends Base and both have method foo() the foo() of child overrides implementation of Base. Similar feature indeed exists in JavaScript.

Solution 2:[2]

if you have following method in your class

public void calculate() {}

Following are some overloaded versions of it.(Note same name)

public void calculate(int i) {}
public void calculate(int i, int j) {}

But following is not an overloaded one of above method. This method differs from the original method only just because the return type. Methods with same signature but with different return types are not allowed in java.

public int calculate(int i) {}

Solution 3:[3]

The method which have same name with multiple definition is known as overloading

may be its differ from argument type and number of arguments.

Example

import java.io.*;
class demoOverloading
{
    int add(int x,int y) //method definition
    {
        return (x+y);
    }
    double add(double x,double y) //method definition
    {
        return (x+y);
    }
}
public class JavaApplication4 
{
    public static void main(String[] args) 
    {
       demoOverloading demo=new demoOverloading(); //creating object for above class
       System.out.println("Sum of Integer "+demo.add(10,20)); //calling integer add method
       System.out.println("Sum of double "+demo.add(33.44,67.5)); //calling double add method
    }
}

The above example having two methods having same name add but one contains int and another contains double arguments, like this we can made with different argument,,

Also possible made difference in number of arguments..

Thank you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AlexR
Solution 2 prageeth
Solution 3