Introduction To Encapsulation
Introduction To Encapsulation
Introduction to Encapsulation
Objectives:
Definitions:
● Encapsulation: The bundling of data (attributes) and methods (functions) that operate on
the data into a single unit (class), while restricting direct access to some of the object’s
components.
● Access Specifiers:
○ public: Members are accessible from outside the class.
○ private: Members are only accessible from within the class.
○ protected: Members are accessible within the class and derived classes (we’ll
explore this more in inheritance).
Why Encapsulation?
Encapsulation allows us to hide the internal details of a class and control how the data is
accessed or modified. By making attributes private, we ensure that they can only be modified
through public methods, ensuring that data is handled correctly.
Example:
class Student {
private:
std::string name;
int age;
char grade;
public:
// Public method to set data
void setDetails(std::string n, int a, char g) {
name = n;
age = a;
grade = g;
}
In this example, the attributes are private, and they can only be modified or accessed using the
public methods setDetails() and printDetails().
Interactive Activity:
● Discussion: Why is it important to control how data in a class is accessed and modified?
What might happen if we allow unrestricted access to all attributes?
● Exercise: Modify the Car class to make all attributes private and add public methods
for setting and getting the values.
Hands-On Exercise:
1. Modify the Rectangle class to make the attributes private. Add public methods to
set the width and height, and to calculate and print the area.
Practice Problems:
1. Encapsulate the Person class: Make the attributes private and add methods to set
and get the person’s details.
2. Create an Account class: Encapsulate the balance and accountNumber attributes of
the BankAccount class. Ensure that deposits and withdrawals can only happen through
public methods.
Wrap-Up:
Homework Assignment:
● Refactor the class from your previous homework to make the attributes private and use
public methods to modify and access the data.