Objective-C的面向对象的三大特征是封装、继承和多态。
1. 封装:
封装是将数据和对数据的操作封装在一个对象中,对象对外部提供接口来访问和修改数据,同时
隐藏了实现的细节。通过封装可以提高代码的安全性和可维护性。
@interface Person : NSObject
@property NSString *name;
@property NSInteger age;
- (void)sayHello;
@end
@implementation Person
- (void)sayHello {
NSLog(@"Hello, my name is %@ and I am %ld years old.", self.name, self.age);
}
@end
Person *person = [[Person alloc] init];
person.name = @"Alice";
person.age = 25;
[person sayHello];
2. 继承:
继承允许一个类继承另一个类的属性和方法,通过继承可以实现代码的重用和扩展。子类可以继
承父类的属性和方法,并且可以添加自己特有的属性和方法。
@interface Student : Person
@property NSString *major;
- (void)study;
@end
@implementation Student
- (void)study {
NSLog(@"I am a student majoring in %@.", self.major);
}
@end
Student *student = [[Student alloc] init];
student.name = @"Bob";
student.age = 22;
student.major = @"Computer Science";
[student sayHello];
[student study];
3. 多态:
多态允许不同的对象对相同的消息作出不同的响应,对象的实际行为取决于其实际类型。通过使
用基类指针或引用来调用派生类的方法,可以实现多态。
@interface Shape : NSObject
- (void)draw;
@end
@implementation Shape
- (void)draw {
NSLog(@"Drawing a shape.");
}
@end
@interface Circle : Shape
@end
@implementation Circle
- (void)draw {
NSLog(@"Drawing a circle.");
}
@end
@interface Square : Shape
@end
@implementation Square
- (void)draw {
NSLog(@"Drawing a square.");
}
@end
Shape *shape1 = [[Circle alloc] init];
[shape1 draw]; // 输出:Drawing a circle.
Shape *shape2 = [[Square alloc] init];
[shape2 draw]; // 输出:Drawing a square.