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 trialJun Dong
4,754 PointsWhere was the value Yoda for the String characterName passed in?
class PezDispenser { private String characterName;
public PezDispenser(String characterName) { this.characterName = characterName; }
public String getCharacterName(){ return characterName; } }
Please help i don't understand, where was the value Yoda for the String characterName passed in???
PezDispenser dispenser = new PezDispenser("Yoda");
I don't understand how this works, why didn't he do String characterName = "Yoda";?
2 Answers
Gergely Horvath
Courses Plus Student 8,207 PointsThis is how constructors work. Given your code above, when you instantiate PezDispenser, the constructor is automatically run. So for example in an other class, or in your main method, when you need a PezDispenser, you write:
PezDispenser pezDispenser = new PezDispenser ("Yoda");
This is because the constructor method expects a string in its signature.
Gergely Horvath
Courses Plus Student 8,207 PointsYou can initialize multiple variables in your constructor like this:
public class NewClass {
private final int i;
private final int j;
private final char c;
private final String s;
public NewClass(int i, int j, char c, String s) {
this.i = i;
this.j = j;
this.c = c;
this.s = s;
}
}
and you instantiate it like this:
NewClass nc = new NewClass(1, 2, 'c', "string");
Jun Dong
4,754 PointsThank you so much there's a lot of things he say that confuses me so thanks you
Jun Dong
4,754 PointsJun Dong
4,754 PointsWhat if there's multiple strings?