黑马程序员技术交流社区

标题: 用"学生用电脑玩游戏"说明对象与对象之间的依赖关系 [打印本页]

作者: bdw9005    时间: 2015-9-13 09:15
标题: 用"学生用电脑玩游戏"说明对象与对象之间的依赖关系

Computer.h
  1. #import <Foundation/Foundation.h>

  2. @interface Computer : NSObject
  3. {
  4.     NSString *_size;
  5.     float _inch;
  6. }
  7. //setter方法:传入尺寸\型号
  8. -(void)setSize:(NSString *)size;
  9. -(void)setInch:(float)inch;

  10. //getter方法
  11. -(NSString *)size;
  12. -(float)inch;
  13. //game方法
  14. -(void)startGame;
  15. @end
复制代码
Computer.m
  1. #import "Computer.h"

  2. @implementation Computer

  3. //setter方法:传入尺寸\型号
  4. -(void)setSize:(NSString *)size{
  5.     _size=size;
  6. }
  7. -(void)setInch:(float)inch{
  8.     _inch=inch;
  9. }

  10. //getter方法
  11. -(NSString *)size{
  12.     return _size;
  13. }
  14. -(float)inch{
  15.     return _inch;
  16. }

  17. //game方法
  18. -(void)startGame{
  19.     NSLog(@"游戏启动, w a s d ....");
  20. }
  21. @end
复制代码

Student.h
  1. #import <Foundation/Foundation.h>
  2. #import "Computer.h"

  3. @interface Student : NSObject
  4. {
  5.     NSString * _name;
  6.     int _age;
  7. }
  8. //setter方法设置属性
  9. -(void)setName:(NSString *)name;
  10. -(void)setAge:(int)age;
  11. //getter方法读取内容
  12. -(NSString*)name;
  13. -(int)age;
  14. //调用电脑用来玩游戏
  15. -(void)playGames:(Computer*)computer;
  16. @end
复制代码

Student.m 注意该类中的方法     依赖关系,学生类 依赖 电脑类  -(void)playGames:(Computer*)computer;
  1. #import "Student.h"

  2. @implementation Student
  3. //setter方法设置属性
  4. -(void)setName:(NSString *)name{
  5.     _name=name;
  6. }
  7. -(void)setAge:(int)age{
  8.     _age=age;
  9. }
  10. //getter方法读取内容
  11. -(NSString*)name{
  12.     return _name;
  13. }
  14. -(int)age{
  15.     return _age;
  16. }
  17. //调用电脑用来玩游戏

  18. -(void)playGames:(Computer*)computer{

  19.     [computer startGame];
  20. }
  21. @end
复制代码

main.m
  1. #import <Foundation/Foundation.h>
  2. #import "Student.h"

  3. int main(int argc, const char * argv[]) {
  4.     @autoreleasepool {
  5.         Student *stu=[Student new];//初始化学生
  6.         
  7.         [stu setName:@"小米"];//设置姓名
  8.         [stu setAge:18];//设置年龄
  9.         
  10.         Computer *computer=[Computer new];//初始化电脑
  11.         [computer setSize:@"acer 4738g"];//设置型号
  12.         [computer setInch:18.9f];//设置尺寸
  13.         
  14.      
  15.         NSLog(@"%d岁的%@在使用%.2f寸的%@电脑玩游戏",[stu age],[stu name],[computer inch],[computer size]);
  16.         [stu playGames:computer];//调用玩游戏的方法
  17.     }
  18.     return 0;
  19. }
复制代码








欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2