1、objc里的协议与java中的接口是同一个东西
2、协议可以遵从协议
2、说法:类Fraction遵从了Printing1、Printing3
//Fraction.h================================ #import <Foundation/Foundation.h> #import "Printing.h" @interface Fracion : NSObject<Printing1,Printing3>{ int numerator; int denominator; } -(Fraction*) initWithNumerator:(int) n denominator:(int)d; -(void) setNumerator:(int) n; -(void) setDenominator:(int) d; -(int) numerator; -(int) denominator; @end //Fraction.m================================ #import "Fraction.h" @implementation Fraction -(Fraction*) initWithNumerator:(int) n denominator:(int)d{ self = [super init]; if(self){ [self setNumerator:n]; [self setDenominator:d]; } } -(void) setNumerator:(int) n{ numerator = n; } -(void) setDenominator:(int) d{ denominator = d; } -(int) numerator{ return numerator; } -(int) denominator{ return denominator; } -(void)print1{ NSLog(@"1:%d/%d",numerator,denominator); } -(void)print2{ NSLog(@"2:%d/%d",numerator,denominator); } -(void)print3{ NSLog(@"3:%d/%d",numerator,denominator); }main.m//main.m================ Fraction *frac = [[Fraction alloc] initWithNumerator:3 denominator:5]; <Printing1> p1 = frac; //id<Printing1> p1 = frac; [p1 print1]; id<Printing1,Printing2,Printing3> p2 = frac; [p2 print2]; [p2 print3]; //用于判断对象是否遵从某个协议 if([frac conformsToProtocol:@protocol(Printing1)] &&([frac conformsToProtocol:@protocol(Printing2)] &&([frac conformsToProtocol:@protocol(Printing3)]){ NSLog(@"YES"); }else{ NSLog(@"NO"); } [frac release]; return 0;