Java Java Objects Meet Objects Methods

Why can't we just assign the getter to be equals to the original. public String getCharacterName = characterName;

class PezDispenser {

private String characterName = "Yoda";

public String getCharacterName = characterName;

}

This worked well for me, but is it wrong? or bad code?

1 Answer

Livia Galeazzi
PRO
Livia Galeazzi
Java Web Development Techdegree Graduate 19,906 Points

The getter is supposed to be a method that returns the value. What you created isn't a method, but a new variable. Then you assigned the value of the first variable characterName to the new variable getCharacterName.

This seems to work at first, until you realize that anybody using your code can do something like this:

pezDispenser.getCharacterName = "Darth Vader";

Because your 'getCharacterName' is a variable, and not a method, and it's publicly accessible, it can be assigned any value. Once it gets a new value it will no longer contain "Yoda", even though the other field "characterName" still contains "Yoda". A getter on the other hand dynamically reads the content of the field, and it's impossible to change its behavior from outside the class.

Makes perfect sense now. Thank you! :)