***Student.h***
// @interface接口文件,一个类的开始
// Student是当前的类名
// NSObject是继承的父类
// 类到@end才结束
@interface Student : NSObject {
// 特征
@public // 成员变量可见度
// 成员变量,或实例变量
NSString *_stuName;
NSString *_stuSex;
NSInteger _stuAge;
CGFloat _stuScore;
NSString *_stuHobby;
}
// 行为
- (void)sayHi;
- (void)eat;
- (void)play;
***Student.m***
@implementation Student
- (void)sayHi {
NSLog(@"Hello World!");
}
- (void)eat {
NSLog(@"吃");
}
- (void)play {
NSLog(@"玩");
}
// 重写继承来的init方法
- (id)init {
_stuName = @"李四";
_stuSex = @"男";
_stuHobby = @"女";
_stuAge = 22;
_stuScore = 88;
return self;
}
@end
***main.m***
// 创建一个对象
// 创建对象需要两步:
// 1.给对象开辟空间,开辟对空间内存
Student *stu = [Student alloc];
// 2.对对象进行初始化设置
stu = [stu init];
// 两步合二为一
Student *stu = [[Student alloc] init];
// 通过对象来调用行为
[stu sayHi];
// 操作成员变量
// 对象通过->来访问自己的成员变量
stu->_stuAge = 20;
NSLog(@"%ld", stu->_stuAge);
// 改姓名
stu->_stuName = @"张三";
NSLog(@"%@", stu->_stuName);
初始化对象的方法
main.m
- (id)init {
_mobilePrice = 4800.1;
_mobileName = @"iPhone6";
_mobileScreenSize = 5.5;
return self;
}