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


Class questions.. I don't understand Instance Methods and Class Methods

I've done a lot of my coding in Java. With instance methods and class methods, I don't see exactly what the difference is. I'm use to mutator and accessor methods in Java, so looking at these and the way they're explained in the videos are a bit confusing..

I may have to reference my Ruby for Java Developers book for this, but I just wanted to see if anyone could help clarify it to me.

1 Answer

Stone Preston
Stone Preston
42,016 Points

instance methods are called on an instance of a class whereas class methods are called on the class itself. In other words to use an instance methods you have to create a new object and call it on that whereas you dont have to have an instance of a class to use a class method.

Well here's a second try since my last response didn't save...

If class methods are created to work on a class, then how do they affect the class if there is no instance of the class created. Is it some form of recursion? I don't understand what a class method would change. Are they equivalent to a constructor in Java?

Stone Preston
Stone Preston
42,016 Points

constructors are class methods yes. but class methods can do more than just construct objects, although thats where you see them used most. class methods just cant access instance variables. they can do anything but that. it has nothing to do with recursion. Most of the time class methods dont change stuff but rather do stuff like create an object, perform an operation, etc. they are closer to procedural functions than methods really.

so in java you can use the Math class methods such as sqrt() to get the sqrt of a number. You dont need to create a math object, you just use the sqrt class method and it gives you the sqrt. It doesnt need to know anything about a particular instance, it just performs or does the square root of the number you give it.

Thanks, that Math class example really cleared it up for me.