Interfaces in Objective-C
Interfaces are implemented using protocols in Objective-C. Here’s an example demonstrating the concept:
#import <Foundation/Foundation.h>
#import <math.h>
@protocol Geometry <NSObject>
- (double)area;
- (double)perim;
@end
@interface Rect : NSObject <Geometry>
@property double width, height;
@end
@implementation Rect
- (instancetype)initWithWidth:(double)width height:(double)height {
self = [super init];
if (self) {
_width = width;
_height = height;
}
return self;
}
- (double)area {
return self.width * self.height;
}
- (double)perim {
return 2*self.width + 2*self.height;
}
@end
@interface Circle : NSObject <Geometry>
@property double radius;
@end
@implementation Circle
- (instancetype)initWithRadius:(double)radius {
self = [super init];
if (self) {
_radius = radius;
}
return self;
}
- (double)area {
return M_PI * self.radius * self.radius;
}
- (double)perim {
return 2 * M_PI * self.radius;
}
@end
void measure(id<Geometry> g) {
NSLog(@"%@", g);
NSLog(@"Area: %f", [g area]);
NSLog(@"Perimeter: %f", [g perim]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
Rect *r = [[Rect alloc] initWithWidth:3 height:4];
Circle *c = [[Circle alloc] initWithRadius:5];
measure(r);
measure(c);
}
return 0;
}
In this example, we define a Geometry
protocol (which is similar to an interface) with area
and perim
methods.
We then implement this protocol on Rect
and Circle
classes. Each class provides its own implementation of the area
and perim
methods.
The measure
function takes any object that conforms to the Geometry
protocol and calls its area
and perim
methods.
In the main
function, we create instances of Rect
and Circle
and pass them to the measure
function.
To run this program, save it as Interfaces.m
and compile it with:
$ clang -framework Foundation Interfaces.m -o Interfaces
$ ./Interfaces
The output will be similar to:
<Rect: 0x100503520>
Area: 12.000000
Perimeter: 14.000000
<Circle: 0x100503530>
Area: 78.539816
Perimeter: 31.415927
This example demonstrates how Objective-C uses protocols to achieve interface-like behavior, allowing for polymorphism and abstraction in object-oriented design.