Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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! :)