What's the difference between "class method" and "static method"?
Asked Answered
A

5

32

I've worked with a few different languages such as Java, C#, and Objective-C.

In most languages, methods that don't require an instance of an object are called static methods. However, when it comes to Objective-C, some people get defensive when you call them static methods, and they expect you to call them class methods.

Why are they called class methods instead of static methods? What is the difference between a static method and a class method?

An answered 11/11, 2011 at 3:5 Comment(6)
There is no difference, but classes in Objective-C have Class instances (e.g. +[NSObject class]) which are themselves fully-fledged objects with methods of their own.Armrest
A static method in C++ is like a class method in Objective C, but a static function in C is a different thing altogether. So if you call it a class method it's a little less ambiguous and won't confuse the C programmers, I guess. Since Objective C is a superset of C, you can actually have a static function in Objective C. So there's only one accurate meaning of static in Objective C, and class method isn't it.Bleeding
@SedateAlien -- Yep, and the full "objecthood" of Class instances makes the term "class method" even more confusing.Prima
@DanielRHicks I suppose it makes sense if you think of it as a method of the class object.Armrest
@SedateAlien There's a huge difference between static and class methods. See bbum's answer below.Ulphiah
possible duplicate of What is the difference between class and instance methods?Brougham
M
71

So my question is why are they called class methods instead of a static method? What is the difference between a static method and a class method?

From Wikipedia: Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance.

This describes exactly what Objective-C's class methods are not.

An Objective-C class method very much requires an instance that is the target of the method invocation. That is, it requires an instance of the metaclass that describes the class object being invoked.

Unlike static methods, Objective-C's class methods can be inherited (which, in combination with having the aforementioned self, is exactly why many classes can share a single, simple, implementation of +alloc on NSObject without needing their own custom implementations) and invoking a class method goes through the exact same objc_msgSend* based dispatch mechanism as any other method call site.

Objective-C's class methods can be overridden across the class hierarchy and they can be swizzled. None of which is supported in languages that typically offer static methods in lieu of class methods.

The bottom line is that static methods and class methods are very different. While that difference is mostly transparent for day to day coding purposes, there are still situations where knowing how class methods work can save you a ton of unnecessary lines of code.

For example, you can't do this with static methods:

@interface AbstractClass:NSObject
+ factory;
@end

@implementation AbstractClass
+ factory
{
    return [[[self alloc] init] autorelease];
}
@end

@interface Concrete1:AbstractClass
@end
@implementation Concrete1
@end
@interface Concrete2:AbstractClass
@end
@implementation Concrete2
@end

void foo() {
    Concrete1 *c = [Concrete1 factory];
    Concrete2 *d = [Concrete2 factory];
    ... etc ...
}    
Manxman answered 11/11, 2011 at 4:19 Comment(5)
@bburn, i don't know where you have been getting your java and c++, but static methods inherit just as easily as any other method, as long as the declarations are public. This answer is correct regarding ObjC but its wrong and misleading regarding the supposed distinction between 'class method' and 'static method'; there is no such distinction, other than in your head. Besides, you forgot to mention the only thing that might resemble a distinction: objC classes are themselves objects of metaclass typeHorology
Sorry but i have to -1 you unless you do the right thing and correct all this misleading infoHorology
Really? #4987627 Maybe you should show an example of polymorphic class methods using Java or C++ as an answer.Manxman
And this: #371462Manxman
@Manxman can you please provide an example of any static method which can't be class methodJerboa
G
5

Because it's dynamically bound, not static.

Because it's really a class object's instance method.

Objective-C class method is actually an object's class object's instance method.

It's hard to describe with text. See nice illustration here.

http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html

Glucinum answered 12/3, 2013 at 8:10 Comment(0)
L
4

Though class methods and static methods are in practice the same most of the time, they are different. With static methods the class is acting as a namespace qualifier. With class methods the class itself is an object and so class methods are to the class object exactly the same thing instance methods are to an instance; as a consequence you can do the following

@interface TestClass : NSObject
+ (void)classOrInstanceMethod;
- (void)classOrInstanceMethod;
@end
...
NSArray * arr = [NSArray arrayWithObjects:
                        [[[TestClass alloc] init] autorelease],
                        [TestClass class],
                        nil];
for( id obj in arr )
    [obj classOrInstanceMethod];

which version of classOrInstanceMethod is called depends on whether obj is a class object or and instance. If you are familiar with the factory class pattern, this pattern is part of the Objective-C language.

Landre answered 11/11, 2011 at 5:11 Comment(0)
E
3

This is purely a historical difference, mostly stemming from the fact that Objective-C was developed contemporaneously with C++, and before C++ or later languages like Java and C# had much influence. Objective-C was essentially a port of the Smalltalk object model to C, so its syntax and terminology don't necessarily seem as "C-like" as that used by C++. However, Objective-C was in no way bucking a trend by not using the term "static method", because that trend wasn't well-established back in 1983.

Eggbeater answered 11/11, 2011 at 3:39 Comment(4)
There is also the point that "static" in C++ is 3 ways overloaded. Likely the term was used for "static methods" in part to avoid introducing a new reserved word into the language (the better to maintain compatibility with C).Prima
@Jim Thio: I expect it was down voted because it is wrong. A class method is not the same as a static method in Java.Accouter
I down voted because it is wrong. Both Eonil and bbum explain well the difference. A static function is not very different from a free function. A class method on the other hand is a virtual method on the class object. Since C++ and Java do not have class objects they can't have class methods either.Monotone
It may be true that "static" methods in C++ and Java work differently than class methods in Objective-C and Smalltalk, but I would still call them "class" methods (as does the Java Language Spec: "A method that is declared static is called a class method."). It's just a difference in the nature of the languages. I've always disliked the overloading of "static" in C++ (and everything that was inspired by it) and assumed, like @HotLicks, that it was just to avoid breaking code that a "class" keyword was not introduced.Farleigh
D
-2

Class Method: Class methods in OOP are methods that are bound to a class rather than an instance of the class. They are defined within the class definition and are accessed using the class itself, rather than an instance of the class. @classmethod decorator is used to define a class method.

Whereas

Static Method: In OOPs, a static method is a method that belongs to a class rather than an instance of the class. It is associated with the class itself, rather than with specific objects created from the class. Static methods can be called directly on the class itself without the need to create an instance. Here, @staticmethod decorator is used.

Also, there is another method called instance method. You can read the differences here.

Durrace answered 3/7, 2023 at 11:48 Comment(4)
Why did you give the definition of "instance method" for "class method"? The question is specific to Objective-C. Posting some generic definitions of the (wrong) terms doesn't answer the question at all.Rubellite
OK, but your answer still doesn't really explain the difference, in Objective-C, between class and static methods. And Objective-C doesn't use @classmethod or @staticmethod. The question is specifically asking about Objective-C.Rubellite
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Deicer
If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From ReviewDulcimer

© 2022 - 2024 — McMap. All rights reserved.