類(Class)類可以看成是創(chuàng)建Java 對象的模板,中的數(shù)據(jù)和函數(shù)稱為該類的成員。
類定義以關(guān)鍵字 class 開頭,后跟類名,類定義之后必須是分號或聲明列表,如,我們使用關(guān)鍵字 class 定義Box數(shù)據(jù)類型,如下所示-
class Box {
public:
double length; //Length of a box
double breadth; //Breadth of a box
double height; //Height of a box
}
關(guān)鍵字 public 確定其后的類的成員的訪問屬性,可以從類外部在類對象范圍內(nèi)的任何位置訪問公共成員。您還可以將類的成員指定為私有的private 或受保護protected的修飾符 ,我們將在小節(jié)中討論。
對象是從類創(chuàng)建的實例,以下語句聲明Box類的兩個實例對象 -
Box Box1; //Declare Box1 of type Box
Box Box2; //Declare Box2 of type Box
對象Box1和Box2都有自己的數(shù)據(jù)成員。
可以使用直接成員訪問運算符(.)訪問類對象的公共數(shù)據(jù)成員,讓我們嘗試以下示例以使事情變得清晰起來-
import std.stdio;
class Box {
public:
double length; //Length of a box
double breadth; //Breadth of a box
double height; //Height of a box
}
void main() {
Box box1=new Box(); //Declare Box1 of type Box
Box box2=new Box(); //Declare Box2 of type Box
double volume=0.0; //Store the volume of a box here
//box 1 specification
box1.height=5.0;
box1.length=6.0;
box1.breadth=7.0;
//box 2 specification
box2.height=10.0;
box2.length=12.0;
box2.breadth=13.0;
//volume of box 1
volume=box1.height * box1.length * box1.breadth;
writeln("Volume of Box1 : ",volume);
//volume of box 2
volume=box2.height * box2.length * box2.breadth;
writeln("Volume of Box2 : ", volume);
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Volume of Box1 : 210
Volume of Box2 : 1560
重要的是要注意,不能使用直接成員訪問運算符(.)直接訪問私有成員和受保護成員。
相關(guān)的其他有趣概念,我們將在下面列出的各個小節(jié)中討論它們-
Sr.No. | Concept & 描述 |
---|---|
1 | Class member functions 類成員函數(shù)是一個在類定義中具有其定義或原型的函數(shù),就像其他任何變量一樣。 |
2 | Class access modifiers 類成員可以定義為公共public,私有private或受保護protected成員,默認情況下,成員將被假定為私有private成員。 |
3 | Constructor & destructor 類構(gòu)造函數(shù)是類中的一個特殊函數(shù),當創(chuàng)建該類的新對象時會調(diào)用該構(gòu)造函數(shù)。 |
4 | The this pointer in D 每個對象都有一個特殊的指針 this ,它指向?qū)ο蟊旧怼?/p> |
5 | Pointer to D classes 指向類的指針的操作與指向結(jié)構(gòu)的指針的方法完全相同。實際上,類實際上只是其中包含函數(shù)的結(jié)構(gòu)。 |
6 | Static members of a class 一個類的數(shù)據(jù)成員和函數(shù)成員都可以聲明為static 靜態(tài)的。 |
更多建議: