1 #import <Foundation/Foundation.h>
2
3
4 @interface Animal : NSObject
5 {
6
7 int _age;
8 double _weight;
9 }
10
11 - (void)setAge:(int)age;
12 - (int)age;
13
14 - (void)setWeight:(double)weight;
15 - (double)weight;
16
17 @end
18
19
20 @implementation Animal
21
22 - (void)setAge:(int)age
23 {
24 _age = age;
25 }
26 - (int)age
27 {
28 return _age;
29 }
30
31 - (void)setWeight:(double)weight
32 {
33 _weight = weight;
34 }
35 - (double)weight
36 {
37 return _weight;
38 }
39
40 @end
41
42 @interface Dog : Animal
43 @end
44
45 @implementation Dog
46 @end
47
48 @interface Cat : Animal
49 @end
50 @implementation Cat
51 @end
52
53 int main() {
54
55 Dog *d = [Dog new];
56 d.age = 10;
57
58 Cat *c = [Cat new];
59 c.age = 20;
60
61 NSLog(@"dog's age = %d, cat's age = %d", d.age, c.age);
62
63
64 return 0;
65 }
66 /*
67 什么叫繼承:如代碼可得出
68 1.如果A繼承自B,那么A就含有B的所有成員變量和方法,這就叫繼承。
69
70 好處:
71 1.可以提高代碼復用,把相同代碼抽出來,如抽出Animal類,讓Dog、Cat繼承
72 2.建立了類之間的關系,如Animal是Dog與Cat的父類
73
74
75 Tips:OC中有兩個根類,一個是NSObject、一個是NSProxy。
76 繼承自NSObject可以讓類能調用new創建對象,或者調用alloc、init。
77
78 */