26 August 2011

Class methods in Java vs Objective-C

The are not the same!

Yes, although their usage is the same (singleton methods, factory methods, utility methods)

But actually class methods in ObjC is looks like instance methods. but in java they are t treated differentially than instance methods ..

Watch this example in Java (in seconds we will write it in ObjC and compare the results):


  1. 
  2. public class Abc
  3. {
  4.     public static void main(String[] args)
  5.     {
  6.         B.func();
  7.         // 1- B will inherit `func() from A.
  8.         // 2- `func()` call the method `x()`
  9.         // 3- since `func()` is a static method in Class A, it will reference non-qualified methods as static methods in the same class
 10.         // 4- `func()` will call `x()` from the same class it resids in (class A)
 11.     }
 12. }
 13. 
 14. class A
 15. {
 16.     static void x()
 17.     {
 18.         System.out.println("in A");
 19.         
 20.     }
 21.     
 22.     static void func() 
 23.     {
 24.         x(); // as if we call : A.x();
 25.     }
 26. }
 27. 
 28. class B extends A
 29. {
 30.     static void x()
 31.     {
 32.         System.out.println("in B");
 33.         
 34.     }
 35. }

Will print : in A

Now lets see how Objective C treat the same situation:


  1. //A.h
  2. #import <Foundation/Foundation.h>
  3. 
  4. @interface A : NSObject
  5. 
  6. +(void) x;
  7. +(void) func;
  8. 
  9. @end
 10. 
 11. @implementation A
 12. +(void) x
 13. {
 14.     NSLog(@"in A");
 15. }
 16. +(void) func
 17. {
 18.     [self x];
 19. }
 20. 
 21. @end


  1. //B.h
  2. #import <Foundation/Foundation.h>
  3. #import "A.h"
  4. 
  5. @interface B : A
  6. 
  7. +(void) x;
  8. 
  9. @end
 10. 
 11. @implementation B
 12. 
 13. +(void) x
 14. {
 15.     NSLog(@"in B");
 16. }
 17. 
 18. @end


  1. //Main.m
  2. #import <Foundation/Foundation.h>
  3. #import "B.h"
  4. 
  5. int main(void)
  6. {
  7. 
  8.     [B func];
  9. 
 10.     return 0;
 11. }

Will Print: in B

Conclusion:
class methods in Objective-C differ from Java.
In Java, class methods don't override each other but hide each other. Also, class methods which comes in no context (when don't being called in any other object), it calls the methods in the same class regardless whom object is calling it.
In Objective C, the existence of self keyword in the class methods make it possible to call functions based on the caller itself (self returns to the object/class that calls the function).

No comments: