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 Meet Objects Creating Classes

vikas pal
vikas pal
11,252 Points

Getting confused.

In the video there is:

PezDispensor dispensor=new PezDispensor();

now i want to know why we type the PezDispensor in front of dispensor. is it used to locate the PezDispensor. java file or it is used to use the class and also tell me the use of it there. Also the PezDispensor after new keyword tell me what that does there.

1 Answer

Adrian Orta
Adrian Orta
30,490 Points

You type PezDispensor the same way you type int.

int number; is the same as declaring: PezDispensor dispensor;

Youre declaring what type of object dispensor holds.

The "new" keyword is used to create a new instance of the PezDispensor class. Youre are stating that this is not just any other PezDispensor but a new one. You are creating it. Adding it to your program and inputing it to be stored in the dispensor variable name which holds objects of the PezDispensor type.

Moderator Edit: Moved response from Comment section to Answer section.

vikas pal
vikas pal
11,252 Points

so please tell me what type of PezDispensor is.how pezdispenzor get an object.

Adrian Orta
Adrian Orta
30,490 Points

PezDispensor is the class that was created in the program. You create a class in order to make an entity that has variables and functions that you desire.

Example:

public class Human {
    private String name;

    public Human (String name) {
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

Human is a class and now we need to create an instance of Human. You can imagine this like a world with a population of 0.

Human adam = new Human("Adam");

This would create an instance of the Human class bringing your population in your imaginary world to 1.

vikas pal
vikas pal
11,252 Points

Thank you adrian for clearing my doubt.