f(sixleaves) = sixleaves

重剑无锋 大巧不工

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  95 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks
Person.h
1 #import <Foundation/Foundation.h>
2 
3 @interface Person : NSObject
4 
5 @property int age;
6 @property NSString * name;
7 
8 - (id)initWithName:(NSString *)name andAge:(int)age;
9 @end
Person.m
 1 #import "Person.h"
 2 @implementation Person
 3 
 4 - (id)initWithName:(NSString *)name andAge:(int)age
 5 {
 6 
 7     if (self = [super init]) {
 8 
 9         _name = name;
10         _age = age;
11         
12     }
13     return self;
14 }
15 @end
Student.h
 1 #import <Foundation/Foundation.h>
 2 #import "Person.h"
 3 
 4 
 5 @interface Student : Person
 6 
 7 @property int no;
 8 
 9 - (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no;
10 
11 @end
Student.m
 1 #import "Student.h"
 2 
 3 @implementation Student
 4     
 5 - (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
 6 {
 7     
 8     if (self = [super initWithName:name andAge:age])
 9     {
10         _no = no;
11     }
12     return self;
13 
14 }
15 
16 @end
main.m
 1 #import <Foundation/Foundation.h>
 2 #import "Person.h"
 3 #import "Student.h"
 4 
 5 int main()
 6 {
 7 
 8     Student *s = [[Student alloc] initWithName:@"suweipeng" andAge:24 andNo:211106435];
 9     NSLog(@"name is:%@ ,age is:%i, number is:%i", s.name, s.age, s.no);
10     return 0;
11 }
12 
13 /*
14 总结:
15 构造方法的设计原则:
16 父类的属性交个父类构造方法处理,子类的成员变量由子类构造方法处理。
17 
18 
19 @implementation Student    
20 - (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
21 {
22     
23     if (self = [super initWithName:name andAge:age])
24     {
25         _no = no;
26     }
27     return self;
28 
29 }
30 @end
31 
32 如果把这段代码改成如下的坏处是,如果Person类中的age名字变了,在子类中必须得做更改。
33 代码的耦合性强。但如果我们用上面的代码来实现,则子类不用变化,父类怎么变化是父类自己
34 的事情,这其实也就是单一职责~。
35 
36 @implementation Student    
37 - (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
38 {
39     
40     if (self = [super init])
41     {
42         _no = no;
43 
44         self.age = age; // 本质上是调用setter与getter方法。但是setAge这个方法在
45         self.no = no;   // 子类中是不存在的,所以它会沿着superclass指针继续找到其
46                         // 父类,然后调用父类的setAge方法,所以这两句其实也可以改成
47                         // super.age = age, super.no = no;但不建议这么写。
48                         // 程序的耦合性太强。
49     }
50     return self;
51 }
52 @end
53 
54 */
posted on 2015-05-02 16:07 swp 阅读(102) 评论(0)  编辑 收藏 引用 所属分类: objective-c

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理