Khi định nghĩa class, bạn định nghĩa blueprint cho kiểu dữ liệu. Objects là instances của class. Methods và variables cấu thành class gọi là members của class.
Class definition bắt đầu bằng từ khóa class theo sau tên class; body trong cặp ngoặc nhọn. Dạng chung:
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) {
// method body
}
<access specifier> <return type> method2(parameter_list) {
// method body
}
...
<access specifier> <return type> methodN(parameter_list) {
// method body
}
}
Một số điểm quan trọng về classes:
- Access specifiers quy định quy tắc truy cập cho members và class. Nếu không nói, default access specifier cho class type là internal. Default access cho members là private.
- Data type chỉ định kiểu biến, return type chỉ định kiểu dữ liệu method trả về (nếu có).
- Truy cập class members dùng toán tử chấm (.).
- Toán tử chấm liên kết tên object với tên member.