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 trialjohnny lawma
3,298 Pointscan any one explain what is happening in this code? kind of confuse. (java constructor )
class PezDispenser {
final private String characterName;
public PezDispenser(String characterName) {
this.characterName = characterName;
}
public String getCharacterName() {
return characterName;
}
}
i'm little confuse with those characterName.
2 Answers
Steven Parker
231,269 PointsI can relate! I don't like to use the same name for variables and parameters for exactly this reason. But that's what we have here. Now what if we just give the constructor parameter a different name:
public PezDispenser(String nameToSet) { // renamed parameter
characterName = nameToSet; // don't need "this" when names are different
}
Does that help it make more sense?
Zhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,210 Points- characterName is a field defined for class PezDispenser.
- PezDispenser has different looks, just as Lego Toys, you can have Iron Man, SpiderMan and etc. as the look of the PezDispenser.
- In terms of Java, the characterName is referred as "Fields" within the class "PezDispenser"
- For example, we can define a class called Student.java. And a student has firstName, lastName and age. You you can define
class Student{
/* fields */
String firstName;
String lastName;
String age;
/* constructor */
Student(String first, String last, String age) {
this.firstName= first;
this.lastName= last;
this.age= age;
}
/* accessors */
String getName() { return this.firstName+" "+this.lastName; }
}
johnny lawma
3,298 Points/* why do make a new String if the value is store in the field */
Student(String first, String last, String age) {
this.firstName= first;
this.lastName= last;
this.age= age;
}
why do we declare a new student string name, last and age,? if the value is store in the field.
Zhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,210 PointsZhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,210 PointsThose fields define what a student should have.
Therefore, you can define a new student by
Student newStudent = new Student("John","Smith","25");