Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHaley Sun
2,573 PointsHow does Java discern two methods by their signatures?
Hi,
I get the "different signature, different method" concept, but have 1 question: how does the system (or whatever we call the Java interface) "tell" that these two methods are different?
I think the example Craig uses in the video is pretty straightforward, as the first "load" method has no parameters while the second was defined by an int. But in the exercise when the "drive" method is already defined by an int (laps), how can one create a new "drive" method to set the lap to 1 without causing the "already defined" mistake I seem to be getting all the time?
Thanks a bunch!
EDIT: OK I figured out the answer to the exercise question, which is basically Craig's example in reverse, silly me...
But I still would like to know about how "different" signatures have to be for their respective methods to be seen as separate, thanks!
3 Answers
Jeremy Hill
29,567 PointsDifferent signatures are determined by their respective parameters. Here is an example:
public class SomeClass{
public void isExample(int x){ // one argument
//some code
}
public void isExample(int x, int y){ // two arguments
//some different code
}
public void isExample(int x, String string){ // two arguments with different types
//some other different code
}
}
These are all different method signatures. I hope this helps.
Jeremy Hill
29,567 PointsI added a little more code to my last example to signify that you can have all three methods within the same class because they all have different method signatures.
Haley Sun
2,573 PointsThanks for your answer, Jeremy! So different types or different amount of the same type = different methods.
I'm guessing if two methods both have the same amount of the same variable type, the system would see them as the same? (Regardless of them having different names)
Jeremy Hill
29,567 PointsYes, if you have two methods with the same name and the same parameter types and quantities then the compiler will throw an error.
Jeremy Hill
29,567 PointsJeremy Hill
29,567 PointsThe compiler can only tell the difference when the method signatures are different. If you try to create an exact signature copy the compiler will bark at ya. To do like your example you would do it like this:
This signature would call the other drive method and give it a 1 for the argument.