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 trial

Java

Haley Sun
Haley Sun
2,573 Points

How 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!

The 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:

public void drive(){
  this.drive(1);
}

This signature would call the other drive method and give it a 1 for the argument.

3 Answers

Different 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.

I 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
Haley Sun
2,573 Points

Thanks 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)

Yes, if you have two methods with the same name and the same parameter types and quantities then the compiler will throw an error.