Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?
The Apple's documentation for NSObject's init method provides some discussion:
"Every class must guarantee that the init method either returns a fully functional instance of the class or raises an exception. Subclasses should override the init method to add class-specific initialization code."
"If a subclass does any initialization of its own, it must define its own designated initializer. This method should begin by sending a message to super to invoke the designated initializer of its superclass."
However, nothing is specified for the case when a subclass needs no extra initialization code.
The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.
Explanatory Code:
@interface ClassA : NSObject {
NSInteger x;
NSInteger y;
}
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;
@end
@implementation ClassA
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
if(self = [super init]) {
x = initX;
y = initY;
}
return self;
}
@end
@interface ClassB : ClassA {
//no extra variables
}
//some extra static methods add to provide some differences
// between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;
@end
@implementation ClassB
/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
// with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
if(self = [super initWithX:initX Y:initY]) {
/* Don't need class-specific initialization code */
}
}
//some extra static methods add to provide some differences
// between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}
@end