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

What does this line of code do in java?

What exactly does the line of code do in example.java?

PezDispenser dispenser = new PezDispenser("Donatello");

The code works fine for me, I'm just confused at the purpose of it.

1 Answer

It declares a variable called dispenser, that is of type PezDispenser and then sets it equal to a new PezDispenser object that has the String "Donatello" passed into it's constructor.

Fundamentally it is not that different from something like this:

int integer = 1;

You first define the type (int in my example, PezDispenser in your example) then the variable name (integer || dispenser) then you set that variable equal to a value, in my example that value is a number, and in your example that is a new instance of the PezDispenser object, which is created by calling it's constructor, more specifically you are calling a constructor that takes 1 String argument.

You don't provide the code for the PezDispenser class, and I don't really remember how it looks at this point since It's been quite a while since I went through the tutorial. But let's say the class's code looks like this

public class PezDispenser {
  public String mName;

  public PezDispenser(String name) {
     mName = name;
  }
}

If that is the code of the class then the line in your example would pass the string "Donatello" into the constructor of the class, constructors are somewhat like methods but they have to be named the same as the class and you don't specify a return type, as a constructor always returns the class itself.

The constructor I have written above simply assigns the string you give it to a field variable called mName.

This means that after running the code in your example your dispenser variable would contain a PezDispenser object with a field variable called mName set to "Donatello".

Which you could access like this:

dispenser.mName

And which could also (more commonly) be used by the functions you have defined within your PezDispenser class.

That explanation didn't end up as quite a simple as I was hoping for but hopefully it cleared some stuff up for you, if you are still confused about something then feel free to ask follow up questions.

This helped sooo Much! Thank You!