Logout

D.2.4

Explain the advantages of encapsulation.

 

Teaching Note:

For example, the scope of data should be confined to the object in which it is defined as far as possible in order to limit side effects and dependencies.

 

Sample Question:

sdfsdfsf

JSR Notes:


We keep our attributes private - that in a nutshell is encapsulation - so that no other classes of objects can "mess with" our attributes. The BankAccount class makes for a good, classic example: only the BankAccount instance should be able to work directly with the attributes savingsBalance, or checkingBalance. Otherwise, someone else could program something to directly access those attributes and change them.

class BankAccount{


...
private double savingsBalance = 100;
...
public void adjustSavingsBalance(Code authenticationCode, String password, double amount){
for(int i = 0; i < codes.length; i++){
if(codes[i].getAuthenticationCode == authenticationCode && codes[i].getPassword.equals(password)){
savingsBalance += amount;
}
}
}

A person wishing to use a certain BankAccount instance would go, from another class


Code myAuthenticationCode = new authenticationCode("John Rayworth", 123412134);


bankAccountInstnace.adjustSavingsBalance(myAuthenticationCode-10, good@#$pass987word);

If they tried to go:


bankAccountInstnace.savingsBalance = -99999;

It would not work, because savingsBalance cannot be directly accessed outside of the BankAccount class.

 

 

Without encapsulation - i.e. a "public", or just non-private double savingBalance


double savingsBalance = 100;

the line


bankAccountInstnace.savingsBalance = -99999;

would, unfortunately work!

 

Taking this real OOP example, and looking at the teaching note:

For example, the scope of data should be confined to the object in which it is defined as far as possible in order to limit side effects and dependencies.

The idea is that the "scope" of the data savingsBalance is indeed confined to its instance of the BankAccount class, and this limits it being used directly. The direct result of what happens in the example is less of a "side effect" than a blatant use of it in a way not intended, but both could potentially happen to data not protected by encapsulation.