黑马程序员技术交流社区
标题:
用"学生用电脑玩游戏"说明对象与对象之间的依赖关系
[打印本页]
作者:
bdw9005
时间:
2015-9-13 09:15
标题:
用"学生用电脑玩游戏"说明对象与对象之间的依赖关系
Computer.h
#import <Foundation/Foundation.h>
@interface Computer : NSObject
{
NSString *_size;
float _inch;
}
//setter方法:传入尺寸\型号
-(void)setSize:(NSString *)size;
-(void)setInch:(float)inch;
//getter方法
-(NSString *)size;
-(float)inch;
//game方法
-(void)startGame;
@end
复制代码
Computer.m
#import "Computer.h"
@implementation Computer
//setter方法:传入尺寸\型号
-(void)setSize:(NSString *)size{
_size=size;
}
-(void)setInch:(float)inch{
_inch=inch;
}
//getter方法
-(NSString *)size{
return _size;
}
-(float)inch{
return _inch;
}
//game方法
-(void)startGame{
NSLog(@"游戏启动, w a s d ....");
}
@end
复制代码
Student.h
#import <Foundation/Foundation.h>
#import "Computer.h"
@interface Student : NSObject
{
NSString * _name;
int _age;
}
//setter方法设置属性
-(void)setName:(NSString *)name;
-(void)setAge:(int)age;
//getter方法读取内容
-(NSString*)name;
-(int)age;
//调用电脑用来玩游戏
-(void)playGames:(Computer*)computer;
@end
复制代码
Student.m 注意该类中的方法 依赖关系,学生类 依赖 电脑类
-(void)playGames:(Computer*)computer;
#import "Student.h"
@implementation Student
//setter方法设置属性
-(void)setName:(NSString *)name{
_name=name;
}
-(void)setAge:(int)age{
_age=age;
}
//getter方法读取内容
-(NSString*)name{
return _name;
}
-(int)age{
return _age;
}
//调用电脑用来玩游戏
-(void)playGames:(Computer*)computer{
[computer startGame];
}
@end
复制代码
main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu=[Student new];//初始化学生
[stu setName:@"小米"];//设置姓名
[stu setAge:18];//设置年龄
Computer *computer=[Computer new];//初始化电脑
[computer setSize:@"acer 4738g"];//设置型号
[computer setInch:18.9f];//设置尺寸
NSLog(@"%d岁的%@在使用%.2f寸的%@电脑玩游戏",[stu age],[stu name],[computer inch],[computer size]);
[stu playGames:computer];//调用玩游戏的方法
}
return 0;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2