开发者

What are the differences and benefits from class level methods in Objective-C compared to Java

开发者 https://www.devze.com 2023-03-10 21:36 出处:网络
For instance, I know Objective-C 开发者_JS百科class methods could be overridden and Java\'s not.

For instance, I know Objective-C 开发者_JS百科class methods could be overridden and Java's not.

What's the benefit of this and what other diferences are there?


In a nutshell, static methods in Java are just functions that are attached to a class. They don't work like instance methods in that you can't use this or super. They effectively have no real concept of them being in a class.

Objective-C class methods are very different though. They are exactly the same as instance methods, except on a class. This isn't too surprising given that classes are objects in Obj-C. As such they go through all the same dynamic dispatch, you can use self to access other class methods, you can use super to call into the superclass's class methods. This allows for a lot more flexibility as you can do all the same stuff with class methods as you can with instance methods, such as nil messaging, method swizzling etc.


Mark Pilkington's answer is correct. Here's is a concrete example illustrating what you can do with Objective-C class methods but not with Java static methods.

Objective-C

@interface Parent : NSObject
+ (int)foo;
+ (int)bar;
- (void)printMyFoo;
@end

@interface Child : Parent
+ (int)bar; // Override bar only.
@end

@implementation Parent
+ (int)foo {
    return [self bar];
}

+ (int)bar {
    return 0;
}

- (void)printMyFoo {
    NSLog(@"%d", [[self class] foo]);
}
@end

@implementation Child
+ (int)bar {
    return 1;
}
@end

Now if you call printMyFoo on an instance of a Parent and Child, you'll get different results because +[Parent foo] dynamically dispatches the bar call at runtime:

id parent = [[Parent alloc] init];
id child = [[Child alloc] init];
[parent printMyFoo]; // -> 0
[child printMyFoo];  // -> 1

Java

class Parent {
    static int foo() { return bar(); }
    static int bar() { return 0; }
    void printMyFoo() { System.out.println(foo()); }
}

class Child extends Parent {
    static int bar() { return 1; }
}

Now if you call printMyFoo() on a Parent and Child instance, they'll both print the same thing because even for the child, Parent.foo() calls Parent.bar() instead of Child.bar():

Parent parent = new Parent();
Child child = new Child();
parent.printMyFoo(); // -> 0
child.printMyFoo();  // -> 0


This is what the Java documentation on Oracle (originally Sun) says about Class variables and methods: http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号