5

As I've learned, in Java method overloading, we use same name for all overloaded methods. And also, their return type is not a matter. But what happens if we use same method as static and non-static form, as in the below example? Can we consider this method overloading?

class Adder {

    static int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }

}

class Test {

    public static void main(String[] args) {
        Adder a1 = new Adder();

        System.out.println(Adder.add(11, 11));

        System.out.println(a1.add(11, 11, 51));

    }
}

I read some articles, but they didn't clarify my question.

Kevin J. Chase
  • 3,856
  • 4
  • 21
  • 43
Kash
  • 329
  • 3
  • 15
  • Have you tested this code yourself? The two methods don't have the same signature, so static should not matter here with regard to the JVM's ability to know which method to call. – Tim Biegeleisen Mar 26 '17 at 03:56
  • read this thread http://stackoverflow.com/questions/2475259/can-i-override-and-overload-static-methods-in-java – Mohd. Shariq Mar 26 '17 at 04:04
  • Yes, I've already run this code and it runs without any error. What I want is to know the concept behind this. Thank you for the link:) – Kash Mar 26 '17 at 04:10
  • 1
    Possible duplicate of [are static and non static overloads each other](https://stackoverflow.com/questions/29581500/are-static-and-non-static-overloads-each-other) – Number945 Apr 08 '18 at 12:50

3 Answers3

4

Use of keyword static doesn't make a difference in method overloading.

Your code compiles because the method signature of both add() methods are different (2 params vs 3 params).

However, if you were to write something like this, then it would result in a compilation error.

class Adder {
    static int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b) {
        return a + b;
    }
}
Mandar Pande
  • 12,250
  • 16
  • 45
  • 72
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
1

Yes they can overload each other. See this JLS :

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

See this Thread .

Number945
  • 4,631
  • 8
  • 45
  • 83
0

U have two methods one is static and another is non static.. so this is not overloading... Because both methods get stored in memory saperately...

  • This is wrong. The difference between static and non-static methods is just a bit flag. They both go where the methods go in a class file format. – Deadbeef Dec 21 '20 at 12:02