Abstraction (trừu tượng) chỉ cung cấp thông tin cần thiết cho bên ngoài, giấu chi tiết triển khai. Dựa trên tách biệt interface (giao diện) và implementation (triển khai).
Class trong C++ cung cấp abstraction: public methods cho bên ngoài thao tác, giữ nội bộ riêng tư. Người dùng dùng class mà không cần biết bên trong triển khai như thế nào.
Ví dụ
#include <iostream>
using namespace std;
class Abstraction {
private:
int length, breadth;
public:
void setValues(int l, int b) {
length = l;
breadth = b;
}
void calcArea() {
cout << "Length = " << length << endl;
cout << "Breadth = " << breadth << endl;
cout << "Area = " << length * breadth << endl;
}
};
int main() {
Abstraction obj;
obj.setValues(5, 20);
obj.calcArea();
return 0;
}
Kết quả
Length = 5 Breadth = 20 Area = 100
length, breadth private. Public methods setValues() và calcArea() cung cấp interface. Class này thể hiện abstraction.
class Abstraction {
private:
int length, breadth;
public:
void setValues(int l, int b) {
length = l;
breadth = b;
}
void calcArea() {
cout << "Length = " << length << endl;
cout << "Breadth = " << breadth << endl;
cout << "Area = " << length * breadth << endl;
}
};
Hàm main()
Abstraction obj;
obj.setValues(5, 20);
obj.calcArea();