-1

I am trying to understand overloading at the moment and am a bit confused. I understand that when calling the same method, it cannot have the exact same arguments. For instance a method called with 2 int variables and then another with two different int variables. But if I use an int and a float, it would be okay. I know the return type does not matter, but what about it being a public or private method. Would this matter?

For instance, say I call public int name(int x) would I be able to call private int name(int x)?

Am I correct in assuming public double name(String x) would also cause overloading in the class? Also is public int name(int x, String y) valid? Passing a string argument into an int function? Would this cause overloading or an error?

EDIT: Do not believe this question is duplicate, my main question is the difference between the public and private, are they method or different and would it cause overloading. Did not see that addressed in other question.

still2blue
  • 193
  • 1
  • 18
  • 4
    Instead of asking us if it's valid, why don't you try it yourself? Discovering is the best way of learning. – Manu Apr 01 '15 at 17:43
  • Sorry am not at my developer computer and have no Java installed on this PC, I certainly agree with you though! – still2blue Apr 01 '15 at 17:49
  • @Manu Trial and error doesn't necessarily guarantee something will always work. The behavior could be undefined or implementation specific. – Uyghur Lives Matter Apr 01 '15 at 18:59

1 Answers1

3

From the Oracle tutorial:

Overloaded methods are differentiated by the number and the type of the arguments passed into the method.

...

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

So no the access modifier doesn't count. You cannot have both public int name(int x) and private int name(int x).

Am I correct in assuming public double name(String x) would also cause overloading in the class?

Yes since it has the same name but with a different parameter type.

Also is public int name(int x, String y) valid? Passing a string argument into an int function? Would this cause overloading or an error?

Again, since it has the same method name but with different parameter types, it is an overloaded method.

Community
  • 1
  • 1
M A
  • 71,713
  • 13
  • 134
  • 174
  • Okay so `public int name(int x)` and `private int name(int x)` would not cause overloading? Because of the public and private are these then two completely different methods inside the class? Thank you for your response, I understand the rest. – still2blue Apr 01 '15 at 17:47
  • @still2blue The two methods would not even compile together. `private` or `public` is not used to determine if the methods are overloaded. – M A Apr 01 '15 at 17:50