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 (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'.