在Objective C中,继承使用关键字“:”,子类可以继承父类的所有方法和属性,同时子类可以添加自己的方法和属性。使用继承时可以用super关键字去调用父类的方法。多重继承在Objective C中不被支持,但可以通过协议来实现类似接口的功能。以下是一个简单的代码示例:
// 父类 @interface Animal : NSObject
@property (nonatomic, strong) NSString *name;
- (void)sayHello;
@end
@implementation Animal
- (void)sayHello { NSLog(@"Hello, I'm %@.", self.name);
}
@end
// 子类 @interface Dog : Animal
@property (nonatomic, strong) NSString *breed;
- (void)shakeTail;
@end
@implementation Dog
- (void)shakeTail { NSLog(@"%@ is shaking tail.", self.name);
}
@end
//使用示例 Dog *dog = [[Dog alloc] init]; dog.name = @"Lucy"; dog.breed = @"Golden Retriever"; [dog sayHello]; // 输出: Hello, I'm Lucy. [dog shakeTail]; // 输出: Lucy is shaking tail.