If the public method is NOT over-ridden, your class extends the hierarchy, then call the public method, you’ll use the public method declared FARTHEST from you
Say you have a Base class with a public method called “publicMethod”
1 2 3 4 5 6 7 |
@interface Base : NSObject { } -(void)publicMethod ; @end |
Then, you have a Child1 class that derives from Base class. It does not over-ride publicMethod in Base class.
1 2 3 4 |
@interface Child1 : Base { } @end |
Then, you have a Child2 class that derives from Child1 class.
1 2 3 4 |
@interface Child2 : Child1 { } @end |
When you go:
1 2 |
Child2 * child2 = [[Child2 alloc] init]; [child2 publicMethod]; |
It will call on publicMethod in the Base class.
If the public method IS over-ridden, your class extends the hierarchy, then call the public method, you’ll use the public method declared CLOSEST to you
1 2 3 4 5 6 7 |
@interface Base : NSObject { } -(void)anotherPublicMethod ; @end |
1 2 3 4 5 6 7 8 9 10 11 12 |
@interface Child1 : Base { } @end @implementation Child1 -(void)anotherPublicMethod { NSLog(@"Child1.m - calling ANOTHER PUBLIC method"); } @end |
Child2 derives from Child1
1 2 |
@interface Child2 : Child1 @end |
Then you go:
1 2 |
Child2 * child2 = [[Child2 alloc] init]; [child2 anotherPublicMethod]; |
Then it will call Child1’s anotherPublicMethod
Cascade – every inheritance node needs to run
If you want a certain method tor un from Base to Child1, to Child2, make sure you use [super …] in the beginning of your call. A great example would be the init method.
Base’s init
1 2 3 4 5 6 7 8 9 |
-(instancetype)init { if(self=[super init]) { NSLog(@"~~~super initialized....now creating Base object~~~~"); NSLog(@"~~~super initialized....now creating Base object~~~~"); return self; } return nil; } |
Child1’s init
1 2 3 4 5 6 7 8 9 10 |
-(instancetype)init { if(self=[super init]) { NSLog(@"~~~super initialized....init Child1 object~~~~"); NSLog(@"~~~super initialized, DONE Child1 object~~~~"); return self; } return nil; } |
Child2’s init
1 2 3 4 5 6 7 8 9 10 11 12 |
@implementation Child2 -(instancetype)init { if(self=[super init]) { NSLog(@"Child2.m - init"); return self; } return nil; } |
Allocating a Child2 object
1 |
Child2 * child2 = [[Child2 alloc] init]; |
would have the result:
— Base.m – creating Base object —
— Child1.m, init Child1 object —
— Child2.m – init Child2 object
Child2’s init calls [super init], which is Child1’s init
Child1’s init calls [super init], which is Base’s init
Base’s init calls [super init], which is NSObject’s init
When NSObject’s init returns, our execution moves forward and displays Base init method’s log
When Base init method returns, our execution moves forward and displays Child1’s init method’s log
When Child1’s init method returns, execution moves forward and displays Child2’s init method’s log.
Hence, we have
— Base.m – creating Base object —
— Child1.m, init Child1 object —
— Child2.m – init Child2 object