Here's my take on this one, notice the self statements in the methods:
// Chapter 10 Exercise 2
// Given that you label the method developed in exercise 1 the designated initializer
// for the Rectangle class, and based on the Square and Rectangle class definitions
// from Chapter 8, add an initializer method to the Square class according to the
// following declaration:
// -(id) initWithSide: (int) side;
// main.m
#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "Square.h"
int main (int argc, char * argv[]) {
@autoreleasepool {
Rectangle *rect1, *rect2;
rect1 = [[Rectangle alloc] init];
NSLog (@"Rectangle: w = %i, h = %i", rect1.width, rect1.height);
NSLog (@"Area = %i, Perimeter = %i", [rect1 area], [rect1 perimeter]);
NSLog (@" ");
[rect1 setWidth: 5 andHeight: 8];
NSLog (@"Rectangle: w = %i, h = %i", rect1.width, rect1.height);
NSLog (@"Area = %i, Perimeter = %i", [rect1 area], [rect1 perimeter]);
NSLog (@" ");
rect2 = [[Rectangle alloc] initWithWidth: 6 andHeight: 9];
NSLog (@"Rectangle: w = %i, h = %i", rect2.width, rect2.height);
NSLog (@"Area = %i, Perimeter = %i", [rect2 area], [rect2 perimeter]);
NSLog (@" ");
Square *mySquare = [[Square alloc] initWithSide: 5]; // <-- replaced " init]" with " initWithSide: 5]"
// [mySquare setSide: 5]; // <-- Commented to omit
NSLog (@"Square s = %i", [mySquare side]);
NSLog (@"Area = %i, Perimeter = %i", [mySquare area], [mySquare perimeter]);
}
return 0;
}
// Square.h
#import "Rectangle.h"
@interface Square : Rectangle
-(id) initWithSide: (int) side;
-(void) setSide: (int) s;
-(int) side;
@end
// Square.m
#import "Square.h"
@implementation Square
-(id) initWithSide: (int) side
{
self = [super init];
if (self)
self = [self initWithWidth: side andHeight: side];
return self;
}
-(void) setSide: (int) s
{
[self setWidth: s andHeight: s];
}
-(int) side
{
return self.width;
}
@end
// Rectangle.h
#import <Foundation/Foundation.h>
@interface Rectangle: NSObject
@property int width, height;
-(id) init;
-(id) initWithWidth: (int) w andHeight: (int) h;
-(void) setWidth: (int) w andHeight: (int) h;
-(int) area;
-(int) perimeter;
@end
// Rectangle.m
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(id) init
{
self = [super init];
if (self)
[self setWidth: 1 andHeight: 1];
return self;
}
-(id) initWithWidth: (int) w andHeight: (int) h
{
self = [super init];
if (self)
[self setWidth: w andHeight: h];
return self;
}
-(void) setWidth: (int) w andHeight: (int) h
{
width = w;
height = h;
}
-(int) area
{
return width * height;
}
-(int) perimeter
{
return (width + height) * 2;
}
@end
Output:Rectangle: w = 1, h = 1
Area = 1, Perimeter = 4
Rectangle: w = 5, h = 8
Area = 40, Perimeter = 26
Rectangle: w = 6, h = 9
Area = 54, Perimeter = 30
Square s = 5
Area = 25, Perimeter = 20