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,717 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;
    }
}