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 trialJazz Jones
8,535 PointsMethod Overloading
I'm confused with the whole method overloading concept. What exactly is it's purpose? I've watched the video about 5 times and I'm still lost. Also, my code doesn't seem to work like Craig's does.
In the applyGuess method when he throws a new Exception, I'm confused on what we're returning. I don't understand why he created a new variable and put it in the return method.
public boolean appylyGuess(String letters) { if (letters.length() == 0) { throw new IllegalArgumentException("No letter found"); } return applyGuess(letters.charAt(0)); }
And then I don't understand why he deleted the char guessInput line, and put the guessInput string into the isHit call.
do { System.out.print("Enter a letter: "); String guessInput = scanner.nextLine();
try {
isHit = game.applyGuess(guessInput);
isAcceptable = true;
} catch(IllegalArgumentException iae) {
System.out.printf("%s. Please try again. %n",
iae.getMessage());
}
} while (!isAcceptable);
return isHit;
}
I'm not even sure I'm using all of these terms correctly lol. I'm a complete beginner and I'm starting to get really lost, and frustrated. I never realized coding was so hard! I am determined though to learn this skill. Seems like a fun hobby. Any responses would be appreciated! Thanks!
I also don't know how to make that fancy screenshot of my workspace for better formatting
1 Answer
markmneimneh
14,132 PointsHello
Method overload allows you yuse same method name but with different signature.
Let try this (pseudo code):
public Myclass() {
public String myMetod(){
return "hello" }
public String myMetod(){
return "Howdy" }
}
This won't compile becouse you declaring same method twice.
Now let try this (pseudo code):
public Myclass() {
public String myMetod(){
return "hello" }
public String myMetod(String firstname){
return "Howdy" + firstname }
public String myMetod(String firstname, String lastName){
return "Howdy" + firstname + " With last name " + last name; }
}
As you can see, I am using same method name but with different implementations ... this is very useful when writing constructors for a class. with oveloading, you can intialize instance of the class to fit your need.
If this answers your question, please mark the question as answered.
Thank you