Java Java Objects Meet Objects Final

johnny lawma
johnny lawma
3,298 Points

can 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
Steven Parker
203,226 Points

I 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Zhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,208 Points
 /* fields */ 
  String firstName; 
  String lastName;
  String age;

Those fields define what a student should have.

  • the following is called the constructor,
Student(String someFirstName, String someLastName, String someAge) {
    this.firstName= someFirstName;
    this.lastName= someLastName;
    this.age= someAge;
}
  • constructor defines how you will be instantiate a new student.

Therefore, you can define a new student by

Student newStudent = new Student("John","Smith","25");
Zhaopeng Wang
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Zhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,208 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
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.