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

Daniel Bello
Daniel Bello
635 Points

Having Trouble Understanding the concepts

public class Example {

public static void main(String[] args) {
    // Your amazing code goes here...
    System.out.println("We are making a new Pez Dispenser.");
    PezDispenser dispenser = new PezDispenser();
    System.out.printf("The dispenser Character is %s\n", 
                       dispenser.mCharacterName);
}

}

Hey guys I am brand new to programming and I am having trouble understanding the concepts of the code written above (It was the code taken from the video from this lesson). What is "PezDispenser," is that the class that is being called? Also, is "dispenser the variable? I also do not understand the concept of "new" right next to the = sign. Thank you for all the help.

1 Answer

The new keyword is used to indicate that you're creating a new instance of that object. So in your code:

PezDispenser dispenser = new PezDispenser();

Means that you just created a new instance of your PezDispenser class with the variable name of "dispenser"

To be a bit more technical, You created a variable of type "PezDispenser", gave it the name of "dispenser" and then gave it the value of a new instance of your PezDispenser class.