Instagram
youtube
Facebook
Twitter

Encapsulation in OOPS

Encapsulation

Encapsulation is the practice of bundling data and methods that operate on that data within a single unit (class).

Data members are typically declared private or protected within the class, hiding the implementation details from the outside world.

Public member functions( accessors and mutators) provide controlled access to the class’s data.

 

class EncapsulatedClass {

private:

    int privateData;      

public:

    int publicData;     

protected:

    int protectedData;    

};

 

Getter and Setter Methods: Getter and setter methods are used to access and modify the private data members of a class, respectively. This ensures that the data is accessed and modified through controlled methods, allowing you to apply validation and maintain data integrity.

 

class BankAccount {

private:

    double balance;

public:

        void setBalance(double newBalance) {

        if (newBalance >= 0) {

            balance = newBalance;

        }

    }

        double getBalance() {

        return balance;

    }

};


 

Illustration:

class Person {

private:

std::string name;

int age;

public:

Void setName( const std::string& newName ) {

name = newName;

}

std::string getName() const {

return name;

}

void setAge(int newAge) {

age = newAge;

}

int getAge() const {

  return age;

}

};