Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regarding var-args

 
Deepa Chandrashekar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

While studying for the certification, i came across this " Two methods with the same name, return type, access modifier but one contain int var-args and an other contain int[] and THEY ARE NOT DIFFERENT" so i tried to write a simple program for this which is,


The error on Line 15 is "The method arrays(int[]) in the type VarargsArray is not applicable for the arguments (int)"...
Q1) So does it mean i cannot call a method with argument int.
Q2) if i change the second method to private int arrays(int... var)
then will the program execute or will the method be overloading?
Please advise and Thanks in advance!

Regards,
Deepa
 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, please UseCodeTags.

Now, this code wouldn't even compile because two methods have the same name and signature. For the purpose of signatures, yes, int ... values, and int [] values are the same. However, there's a difference in how you call those two methods. In the first case, you can call it with a comma separated list of int values, where a single int value can be thought of as a list with just one value. When you define the parameter as a integer array though, then you must call it with an integer array argument. In either case, you would treat the parameter values as an int array within the method. So varargs are the same as arrays of args in some ways, and different in others.
 
Deepa Chandrashekar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the answer!
My question is if i change the access modifier and return type of second method will it be overloading?
Since var-args are similar to arrays but they cannot be interchangeable.

Please advise

Regards,
Deepa.
 
Roel De Nijs
Sheriff
Posts: 9818
101
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the rule of a valid overload? You MUST change the argument list, you may change return type, access modifier,...

So just changing access modifier and/or access modifier will not be a valid overload. That's something you can easily confirm using Notepad and javac (or using an editor).

Have a look at this thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic