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.

Diwakar Singh
785 PointsHow to use nonstatic method inside the class without an object
He has used isEmpty() method which is non static without creating an object in if(!isEmpty) how this is possible
1 Answer

andren
28,523 PointsHe calls the isEmpty
method within dispense
which is itself a non-static method. That means that there is no way to run that code without first creating an instance of the class.
When Java encounters a call to a method that is found within the object it is treated as a call to that object's method. So isEmpty()
is equivalent to this.isEmpty()
.
Referencing a non-static method or field variable within a class is only an issue if the code is written inside a static method, within non-static methods it poses no problem since an object is guaranteed to exist when the code is ran.
Diwakar Singh
785 PointsDiwakar Singh
785 Pointswhat do you mean by "When Java encounters a call to a method that is found within the object it is treated as a call to that object's method"
andren
28,523 Pointsandren
28,523 PointsI mean that when you call a method that has a name that matches a method that exists in the current object, then it will automatically call that method, even though you did not specify where the method is from.
So if you create an instance of
Dispenser
calleddis
and calleddis.dispense()
when Java encounters the call toisEmpty()
it looks for a method calledisEmpty
within the object stored indis
, and if it finds one it then that is the method it runs.And since you cannot call
dispense
without creating an object first this will always be what happens, which is why calling theisEmpty
method works.