What are the differences and benefits of class-level methods in Objective-C over Java?

For example, I know that the methods of the Objective-C class can be overridden, but Java can not.

What is the use of this and some other differences?

+3
source share
3 answers

In short, static methods in Java are just functions that are bound to a class. They do not work as instance methods because you cannot use this or super. They actually have no real idea that they are in the classroom.

Objective-C . , , . , , Obj-C. , , self , super . , , , nil, swizzling ..

+11

Mark Pilkington . , , Objective-C, Java.

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

, printMyFoo , , +[Parent foo] bar :

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; }
}

, printMyFoo() " ", , Parent.foo() Parent.bar() Child.bar():

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

This is what Oracle's Java documentation (originally Sun) talks about class variables and methods: http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html

0
source

All Articles