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