Encapsulation (đóng gói) gom dữ liệu và phương thức thao tác dữ liệu thành một thành phần duy nhất, bảo vệ khỏi can thiệp bên ngoài. Bản chất: gói gọn dữ liệu và hàm sử dụng dữ liệu. Dẫn đến khái niệm quan trọng: Data Hiding (ẩn dữ liệu).
Trong C++, encapsulation triển khai qua class (kiểu dữ liệu do người dùng định nghĩa) chứa cả dữ liệu và phương thức gói gọn cùng nhau.
Ví dụ
#include <iostream>
using namespace std;
class EncapsulationDemo {
private:
int length, breadth, height;
public:
void setValues(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
void calcVolume() {
cout << "Length = " << length << endl;
cout << "Breadth = " << breadth << endl;
cout << "Height = " << height << endl;
cout << "Volume = " << length * breadth * height << endl;
}
};
int main() {
EncapsulationDemo obj;
obj.setValues(5, 3, 2);
obj.calcVolume();
return 0;
}
Kết quả
Length = 5 Breadth = 3 Height = 2 Volume = 30
Biến length, breadth, height là private. Hàm public setValues() khởi tạo, calcVolume() tính thể tích và in. Điều này thể hiện encapsulation.
class EncapsulationDemo {
private:
int length, breadth, height;
public:
void setValues(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
void calcVolume() {
cout << "Length = " << length << endl;
cout << "Breadth = " << breadth << endl;
cout << "Height = " << height << endl;
cout << "Volume = " << length * breadth * height << endl;
}
};
Hàm main()
EncapsulationDemo obj;
obj.setValues(5, 3, 2);
obj.calcVolume();