天天看點

黑馬程式員------類和對象

                                                                                 -----------android教育訓練、java教育訓練、java學習型技術部落格、期待與您交流!------------

類和對象

1類的聲明和實作

類是對象的抽象,而對象是類的具體執行個體。類是抽象的,不占用記憶體,而對象是具體的,占用存儲空間。類是用于建立對象的藍圖,它是一個定義包括在特定類型的對象中的方法和變量的

 類的聲明(聲明對象屬性“成員變量”初始化為零)

NSObject,目的是讓car這個類具備建立對象的能力

@public可以讓外部的指針間接通路對象内部的成員變量

@interface Car :NSObject
{
@public
int wheels;
int speed;
}
@end
           

1.     類的實作(方法的實作)

@implementation Car
{
}
@end
Int main(  )
{
//利用類建立對象
//在oc中執行一些行為就寫上一個中括号[行為執行者,行為名稱]
//定義了一個指針變量p,p将來指向的是car類型的對象
//[car new]會建立出一個新對象,并且會傳回新對象本身
Car *p = [Car new];
Car *p 1= [Car new];
//給p所指向對象的wheels屬性指派
P→wheels = 4;
p→speed = 200;
P1→wheels = 5;
P1→speed = 300;
Return0;
}
//給p所指向的對象發送一條run消息
[p run]
NSLog(@”學習,科目:%d”, P→wheels, P1→speed,);
           

對象的行為

隻要是oc對象的方法,必須以見好 – 開頭

oc方法中任何資料類型都必須用小括号()擴住

oc方法中的小括号()擴住資料類型

(void)run;
{
NSLog(@”學習”);
}
@end
           

方法與成員變量

 1.類的聲明(成員變量,方法的聲明)

@interface  person : Nsobject
{
Int age;
Double weight
}
(void)walk;
@end

           

1.     類的實作

@implementation 類名
(void)walk
{
Nslog(@”唱了一首歌”,age);

}
@end
Int main()
{
Person *p =[person new];
p→age = 10;
p→weight = 30;
Person *p 2=[person new];
P2→age = 20;
P2→weight = 40;
P = p2;

[p2 walk];
return 0;
           

類跟函數

#import <Foudation/ Foudation .h>
@interface Car : Nsobject
{
Int wheels;
Int speed;
}
-(void)run;
@end
@impiementation  Car
-(void)run
{
NSLog(@”%d個杯子,”,wheels)
}
@end
Void test(int w, int s);
{
w=20;
s = 200;
void test1(Car *newC)
{
newC→wheels = 5;
}
}
Int main( )
{
Car *c = [Car new];
c→wheels = 4;
c→speed = 200;
ttest1(c);
[c run];
Return 0;
}  
           

類的合理設計

Typedef enum{
 SexMan,
SexWoman
}Sex;
Typedef struct{
  Int year;
  Int month;
  Int day;
}Date;
Typedef enum{
ColorBlack,
ColorRed,
ColorGreen
}Color;

#import <Foundation/ Foundation .h>
@interface Student : NSObject
{
@public
Sex sex;
Date birthday;
double weight;
Color favColor;
Char *name;
}
-	(void)cat;
-	(void)run;
-	(void)print;
@end
@implementation Student
-	(void)print
{
NSLog(@”性别=%d,姓名=%s,生日=5d-%d-%d”,sex);
}
-(void)eat
{
Weight +=1;
NSLog(@”吃完後的體重是%f”,weight);
}
-	(void)run
{
Weight -= 1;
NSLog(@”跑完後的體重是%f”,weight);
}
@end
Int main( )
{
Student *s = [Student mew];
s->weight = 50;
s->sex = SexMan;
Date d = {2015,9,19};
s->birthday = d;
s->name = “jack”;
s->favColor = favColorBlack;
[s eat];
[s eat];

[s run];
[s run];
}
           

在類外定義函數時,應指明函數的 作用域 。在成員函數引用本對象的資料成員時,隻需直接寫資料成員名,這時系統會把它預設為本對象的資料成員。也可以顯式地寫出類名并使用域 運算符

在大多數情況下,主函數中甚至不出現控制結構(判斷結構和循環結構),而在成員函數中使用控制結構。

在面向對象的程式設計中,最關鍵的工作是類的設計。所有的資料和對資料的操作都展現在類中。

隻要把類定義好,編寫程式的工作就顯得很簡單了。

繼續閱讀