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

Why getCharacterName gets different values?

PezDispenser dispenser = new PezDispenser("Yoda");
    System.out.printf("This dispenser is %s %n", 
                      dispenser.getCharacterName()
                     );
    String before = dispenser.swapHead("Darth Vader");
    System.out.printf("It was %s but now is %s %n", before, dispenser.getCharacterName());

in the first dispenser.getCharacterName we get Yoda, but in the second we get Darth Vader, why is that? the value of Yoda was transferred to originalCharacterName, so in the method getCharacterName it should return Darth Vader

1 Answer

Gregorio Massara
Gregorio Massara
3,544 Points

The answer I think is in the swapHead method;

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

it returns the originalCharacterName but it also assigns it to the new Character in our case Darth Vader. Hence the confusion...and the need to use the final attribute for the original character to prevent this sort of changes.