Reputation: 339
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.
Upvotes: 6
Views: 9150
Reputation: 1
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...
Upvotes: 0
Reputation: 31851
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;
}
}
Upvotes: 4
Reputation: 4940
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 .
Upvotes: 1