Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading with both static and non-static methods

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.

like image 674
Kash Avatar asked Mar 26 '17 03:03

Kash


1 Answers

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;
    }
}
like image 159
Raman Sahasi Avatar answered Oct 13 '22 03:10

Raman Sahasi