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 Privacy and Methods

Missing something

Can somebody please explain why we do this? PezDispenser dispenser = new PezDispenser();

Sorry, I hope my question is not too stupid, just trying to understand and not to miss anything. thanks in advance!

1 Answer

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hello Federico,

Basically all that we're doing in that line of code is making a new instance of the PezDispenser class that we made.

Since java is one of the most object oriented programming languages, you'll see creating instance of an objects often.

Think of it like creating a person class.

public class Person {
 private String mName;

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

public int getName() {
 return mName;
}

public void greeting(Person person) {
  System.out.printf("Hello %s, it is good to meet you", person.getName();
}

We now have just created the class blueprint for person with a few methods that can be called on it., but we actually don't have a person object yet.

To create one we'd to

Person myself = new Person("Rob Bridges");

Now I'm created as an instance of the object. And I can have unique values stored to myself.

If I were to call greeting(myself);

It would print out "Hello Rob, it is good to meet you.

Let's say we create another instance of the person class.

Person yourself = new Person("Federico");

If we do the same thing and call it on this, it would instead say

"Hello Federico, it is good to meet you."

Think of it like basically creating unique unique people, which can all have similar methods on them, but since they're unique the results can vary.

Thanks, hope this helps.