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

Java doesn't accept new PezDispenser

In the Creating Classes of Java Objects, my code (I believe) is identical to his, but when I compile and run the code, I get this error. Example.java:6: error: constructor PezDispenser in class PezDispenser cannot be applied to given types;
PezDispenser dispenser = new PezDispenser();

I've put a link to a screenshot of my code below

https://w.trhou.se/vdb62xgpjf

1 Answer

If I'm right, your constructor isn't doing what you want it to. In the constructor, if you ware trying to set the member variable characterName to the passed in value of name, you will need to use the this keyword.

Without the this keyword, since no type is declared, referencing characterName in the constructor is trying to find an already declared variable within the constructor scope named character name, and that variable doesn't exist.

see the code below.

class PezDispenser {
   String characterName = "Yoda";

  public PezDispenser(String name) {
    this.characterName = name; //<-- note that the this keyword will reference the member variable of the class when the object in instantiated, in this case, setting it's value to the passed in name value
  }
  public String getCharacterName(){
    return characterName;
  }
}