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

Breaking down of the code

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

What does this mean?

I know it's public so it can be tampered with (I think). Is it giving the object PezDispenser a String value of "characterName"?

"mCharacterName = characterName; " - what does the m mean? A member of what?

I'm getting parts of it, but have been thrown off by a lot of the more technical words.

Kristi Smythe
Kristi Smythe
10,665 Points

Hi Max,

The code snippet you posted is the constructor in your PezDispenser class.

We use a constructor to define a blueprint or signature and what the expectations (parameters) are for this signature.

In this case we are setting up our blueprint or constructor in preparation for instantiating or creating PezDispenser object instances of the PezDispenser class.

In our Example.java file, we utilize this constructor inside the main method by creating an object instance of PezDispenser(String "Yoda"). The part in parenthesis is referred to as an argument. The argument calls the characterName parameter from our constructor signature we created in our PezDispenser class, by specifying it as a String type with the value of "Yoda".

The main method in Example.java is what causes our program to run and deliver output to the console.

Happy coding! kristi

2 Answers

Ricky Catron
Ricky Catron
13,023 Points

What this function does is allow you to pass attributes to an object when you create it.

PezDispenser myPezDispenser = new PezDispenser("CharacterNameHere");

The tells others reading your code that mCharacterName is a member of the object PezDispenser.

This naming convention of adding an m before the variable name. This allows other programmers to read your code easier.

Goodluck! --Ricky

Thanks Kristi Smythe and Ricky Catron. It's all slowly sinking in.