Access Modifiers
Objective-C also provides 3 access modifiers for member variables:
- @public: no access restrictions
- @private: accessible within the defining class
- @protected: accessible within the defining class and by derived classes (default)
- The default access mode is “protected“
- Access modifiers can be applied only to member variables; methods are always public.
Note that the member variables are located in the “{ }” section.
1
2
3
4
5
6
7
8
9
10
11
12
| /* Product.h */@interface Product : NSObject { @private int productId; @public NSString *productName; float price;}-(void) setProductId: (int) n;-(int) getProductId;@end |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| /* Product.m */#import #import "Product.h"@implementation Product-(void) setProductId: (int) n { productId = n;}-(void) getProductId { return productId;}@end |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| /* MainApp.m */#import #import "Product.h"int Test() { Product *p = [Product new]; [p setProductId:100]; p->productName = @"Toy"; p->price = 9.99; NSLog(@"Id: %d", [p getProductId]); NSLog(@"Name: %@", p->productName); NSLog(@"Id: %4.2f", p->price);}... |
No comments:
Post a Comment