Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Meet Objects Final

Thierry van der Zon
Thierry van der Zon
291 Points

It does not give Yoda, but it gives "null"

when i compile this i get "The dispenser is null"

and here is my code. "public class Example {

public static void main(String[] args) { // Your amazing code goes here... System.out.println("We are making a new PEZ Dispenser"); PezDispenser dispenser = new PezDispenser("Chicken"); System.out.printf("The Dispenser is %s %n", dispenser.getCharacterName() ); String before = dispenser.swapHead("Darth Vader"); System.out.printf("It was %s but Chris switched it to %s %n", before, dispenser.getCharacterName()); }

}"

class PezDispenser { private String characterName;

public PezDispenser(String name) { this.characterName = characterName; }

public String getCharacterName() { return characterName; }

public String swapHead(String characterName) { String originalCharacterName = this.characterName;
this.characterName = characterName; return originalCharacterName;

}

}

1 Answer

Samuel Ferree
Samuel Ferree
31,718 Points

Your problem is in your constructor, you are assigned the private member variable "characterName" to itself, and not the passed in variable "name" See below for the correct class implementation

class PezDispenser 
{
    private String characterName;

    public PezDispenser(String name) {
        this.characterName = name; // <---- assign the member variable, to the passed in value.
    }

    public String getCharacterName() {
        return characterName;
    }

    public String swapHead(String characterName) {
        String originalCharacterName = this.characterName;
        this.characterName = characterName; return originalCharacterName;
    }
}