As a developer I am fan of static methods.
Recently I come across difference between OOP languages about this static methods.
All OOP language use static method to access any method without creating instance of than class. So we can call this kind of method with just class name.
But some language allow to access static method from instance variable also like Java and some don’t like Objective – C.
So what is the reason of this kind of difference between two OOP language? Which is correct OOP behaviour? I am just curious to know this.
Static methods have nothing to do with OOP at its core. If Java had no instances of classes, this would be an example of modular programming with classes being modules and static methods being ordinary procedures.
The here relevant difference between Java and Objective-C is that the latter has a Smalltalk-like metaobject protocol: classes themselves are normal objects. A foo
object may be an instance of a FooClass
which eventually is an instance (!= subclass) of NSObject
. When we invoke a method on a class, we send this message to the actual object representing that class. In Java, calling a static method does not involve objects at all, it’s just a procedure call (and can be fully resolved before run time – no dynamic dispatch is needed).
In Java, classes are not reified beyond reflection. So instance.staticMethod()
kind of makes sense, as it couldn’t mean anything else (it just happens to share the syntax for ordinary method calls, but the static method is only looked up according to the static type of the instance
variable.
Objective-C does not have such “static methods”, but it does have:
-
class methods, which resemble static methods if you squint your eyes. It would be very confusing if a method call on an instance would end up being a method call on a class (another object alltogether), so there is no syntactic shortcut like
[instance staticMethod]
, which doesn’t even save that much over[[instance class] staticMethod]
. Such class methods are good for constructors and other factory methods. However, they are not “static” as they are subject to inheritance. -
plain old C functions. These exist outside of objects and classes, and are not subject to dynamic dispatch – which also makes them interesting from a performance standpoint. These are “static” in the actual sense of that word, but they are not “methods”.
3
C++ allows this->staticMethod(), probably so you don’t need to change the source code when you change a method to being static.
Swift allows overloading of class methods. In an instance method, self is the instance, and Self is it’s class, so Self.classMethod() will call different code depending on the runtime type of the instance.
And inside a class method, I believe “self” is the dynamic class that got you there.