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) Harnessing the Power of Objects Incrementing and Decrementing

How was isEmpty() called without an object?

At 05:23 isEmpty() method was called in the if statement without using a PezDispenser object. isEmpty() not being a static method, why was an object not required to call it?

3 Answers

Hi there,

You're inside the class here, so there is no object. The methods within the class can call each other without needing to be via an instance or a class method. They can't do anything until the class has been instantiated, an instance created, but you can create the member variables and instance methods in this way.

So, the helper method isEmpty() which just returns a boolean, can be used in other methods within the class. You can wire up the functionalty of your instance this way.

I hope that helped.

Steve.

I didn't get it completely yet. From little that I understood, an object is not required to call a method that is in the class that contains the aforementioned method but it is required when we have to call the method from another class, is it?

Hi Steve, Can you rephrase your explanation to a more absolute beginner level understanding either by explaining your vocab words like: class, instance, method, instantiated, member variables, instance methods

or can you explain this as a situational metaphor? Like using I don't know, a camping trip or some other example? Thanks!

Hi, abbymann

I wrote a piece about class, objects etc before so, rather than me reinventing the wheel; have a look at this post and see if that helps clarify a few things. It uses a tenuous metaphor to a point - you'll see what I mean.

And the response from Brandon below covers a slightly different aspect to methods. A static method can be called on the class itself without requiring an instance. Both answers are correct and not contradictory. I wrote another answer on class methods - I'll see if I can find that too.

Steve.

Brandon Watts
Brandon Watts
940 Points

Yes Sreerem, unless a method is static, you will need to create an object to access from another class.

Brandon, That's not what the Mod Steve said above, in fact he said the opposite, that there are exceptions to this...can you elaborate what you mean?

Thanks for your help Steve, I appreciate the reply!