开发者

Polymorphism and default implementations in Objective-C

Basically I have a Parent superclass which i.e is called MAMMAL. The mammal by default extends a UIImageview. Now I have tiger class which in turns extend the MAMMAL class and the mammal class has i.e a breastfeedbaby method.

In my mammal.h class, i declare the breastfeedbaby method.

Now , I want to be able to do something like adding a list of animals which extends mammal and have their own breastfeedbaby implementation, loop through and array and just cast to Mammal and do [mammal breastfeedbaby].

I would like each animal to call their own breastfeedbaby method since they all overide it but my issue is that it will call the breastfeedbaby from the mammal.m if i declare it there.

In java i can ei开发者_开发技巧ther use an interface or just have an abstract class with abstract method and have the different implementations override the method.

Does that make sense? My issue is that if i do not omit the breastfeedbaby method in mammal.m it will call the breastfeedbaby method in the mammal.m and if i do ommit the breastfeedbaby method in the mammal.m, the class will be yellow with warnings saying i did not implement the mammal.h class correctly. If I do that the animals' breastfeedbaby method is called. Should I just use a protocol here but from what I understand a protocol is not the same as an interface in java.

I don't know if it makes sense but thanks anyways.


Following scenario:

  • Mammal.h: - (void)method;
  • Mammal.m: - (void)method { NSLog(@"Mammal"); }
  • Monkey.h: @class Monkey : Mammal
  • Monkey.m: - (void)method { [super method]; NSLog(@"Monkey"); }
  • Somewhere.m: Mammal *monkey = [[Monkey alloc] init]; [monkey method];

Should yield:

Mammal

Monkey

UPDATE: of course, you can remove the call to [super method] if you wish. Just showing the possibility.


Objective-C resolves everything dynamically, so it doesn't have abstract base classes or interfaces. The closest you can get to an abstract method is to write a default implementation (in the parent class) that throws an exception.

@implementation Mammal

- (void)breastfeedBaby
{
    [NSException raise:@"MethodNotImplemented"
                format:@"Class %@ failed to implement required method %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}

@end

It would be nice to catch missing methods at compile-time, but that just isn't possible in a language with dynamic typing.


Even if you cast an object as a MAMMAL, it will still call the -breastfeedbaby method for whatever subclass it is. This is because Objective-C uses message sending.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜