What's the difference between a class method and an instance method?
Are instance methods the accessors (getters and setters) while class methods are pretty much everything else?
Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class.
An instance method is a method that belongs to instances of a class, not to the class itself. To define an instance method, just omit static from the method heading. Within the method definition, you refer to variables and methods in the class by their names, without a dot.
Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:
@interface MyClass : NSObject + (void)aClassMethod; - (void)anInstanceMethod; @end
They could then be used like so:
[MyClass aClassMethod]; MyClass *object = [[MyClass alloc] init]; [object anInstanceMethod];
Some real world examples of class methods are the convenience methods on many Foundation classes like NSString
's +stringWithFormat:
or NSArray
's +arrayWithArray:
. An instance method would be NSArray
's -count
method.
All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:
A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.
An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With