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

Vinay Mishra
Vinay Mishra
5,496 Points

PezDispenser dispenser = new PezDispenser();

Why did we write this in the code:

PezDispenser dispenser = new PezDispenser();

I do not understand its utility.

4 Answers

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Vinay,

PezDispenser dispenser = new PezDispenser();

with this code we create a new object of the PezDispenser class.

I would like to use a different example then PezDispenser that hopefully will help you understand this very important part of OOP (object oriented programming). So let me take you into the Java Jungle :)

Before you create a new object you need to build a parent class, we can create an instance of.

We call our parent class Animals and we will create an object of that class and call it "tiger". Tigers are animals right ....

public class Animal {
// Animals class
}

In Java everething is an object. So you need to create objects/instants of a class somewhere in your code if you need it. With the "new" keyword you instantiate a new object. Instance is a another word for Object.

So it should look like this:

Animal tiger = new Animal();
//on the left side you see the Declaration: you declare a an object/instance "tiger" of Type/Class Animal
//on the right side you see the Instantiation: The new keyword is a Java operator that creates the object (in instantiates a new object
//Initialization: The "new" operator is followed by a call to a constructor, which initializes the new object

A class is like a blueprint for objects. Inside that class you can declare methods and variables and access them after instantiating (new Animal()).

Hope it helps to survive in the Java Jungle ...

Grigorij

Vinay Mishra
Vinay Mishra
5,496 Points

That was very helpful Grigorij. Thanks a lot!

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

:))))

I will give my best, promise !

Thanx

faraz
faraz
Courses Plus Student 21,474 Points

Great explanation Grigorij! Keep up the good work!

Awesome Grigorij! Nice job man! Thanks so much...I had the same question as Vinay

Thanks @Grigorij Schleifer ..Thaks A lot :)

Thanks a lot Grigorij