Java Java Objects Meet Objects Final

Dinu Comendant
Dinu Comendant
2,791 Points

Why getCharacterName gets different values?

PezDispenser dispenser = new PezDispenser("Yoda");
    System.out.printf("This dispenser is %s %n", 
    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

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.