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 (Retired) Meet Objects Constructors

What is the purpose of < = "Yoda">?

Here are two blocks of code:

public class PezDispenser {

private  String mCharacterName;

public PezDispenser(String nameOfCharacter) {
    mCharacterName = nameOfCharacter;
}

public String getCharacterName() {

    return mCharacterName;
}

}

AND

public class PezDispenser {

private  String mCharacterName = "Yoda";

public PezDispenser(String nameOfCharacter) {
    mCharacterName = nameOfCharacter;
}

public String getCharacterName() {

    return mCharacterName;
}

}

Does < = "Yoda"> play any role in the code? The code runs without < = "Yoda">.

3 Answers

the difference is the bottom code will keep returning "yoda" because it is the fixed mCharacterName. But in the top code where mCharacterName isn't defined you have the capability to change it to whatever you want. In the video when he changes the code in Example.java; the line of code that says: PezDespenser dispenser = new Pezdespenser("donatello"); It allows us to change the name to donatello; but if the user wanted something else like spongebob, mickey etc. we would have the capability to do it. Hope it helps!

kabir k
PLUS
kabir k
Courses Plus Student 18,036 Points

In the 1st example, the private field, mCharacterName, is declared but not set or initialized. So upon creating or instantiating a PezDispenser object, the PezDispenser constructor (which has the same name as its class) will require you to pass in an String argument. But this way you change or modify mCharacterName value to any character name that you want (at the instantiation of the PezDispenser class)

In the 2nd example, you've declared and initialized a value for the private member variable, mCharacterName. This way, you've hardcoded the mCharacterName value to "Yoda"

Hope that helps.

There's very little difference by the end of those two code blocks.

In the first block of code, without [ = "Yoda" ], the mCharacterName property has no value, is undefined, until the object constructor assigns it the value of 'nameOfCharacter'.

In the second code block, the mCharacterName briefly has a value of "Yoda" before it is overwritten by the object constructor assigning it the value of 'nameOfCharacter'.