Encapsulation
One of the most important features of Object-Oriented Programming is encapsulation.
encapsulation¶
Hiding internal state and requiring all interaction to be performed through an object's methods.1
Encapsulation insulates changes from propagating throughout your program.
- This is good because if a private part is changed, that change is constrained to the class in which it was defined.
To increase encapsulation, you should:
-
Give fields and methods the most restricted access possible.
-
Make all fields
privateand provide non-private methods to access and modify (or mutate) them.
mutate¶
A fancy word for change. A method that sets a
privatefield could be called a mutator. Similarly, a method that retrieves the value of aprivatefield could be called an accessor. Or we could just call them a setter and a getter.
The goal of encapsulation is to keep users from changing data you don't want them to change, or changing it in a way we don't want them to.
Practice Exercise¶
Allowing other code to access fields directly could create an unwanted dependency. This means other code expects our code to work a certain way.
If we change a field's visibility later, we risk breaking other code that depends on our field being visible.
Practice good encapsulation from the start.
Drill¶
Encapsulation/com.example.encapsulation.drills.BankApp
Encapsulation/com.example.encapsulation.drills.AccountYou have already made the
accountIdandbalancefields private inAccount. * Add fourpublicmethods toAccount. *getAccountId()to allow users to retrieve theaccountId. *setAccountId(String id)to allow users to set theaccountIdfield by passing a new value. * Aget-andset-method for thebalance. * Call the methods fromBankApp.(Solution:BankApp2.java, Account2.java)
Drill¶
Encapsulation/com.example.encapsulation.drills.StudentWhat two things can we do to improve the encapsulation of this class (choose two)? * [ ] Make the classpublic class Student{ int[] scores; private double average; public int[] getScores(){ return scores; } public double getAverage(){ return average; } private void computeAverage(){ // valid code to compute average // average = update average value } public Student(){ computeAverage(); } }private. * [ ] Make the scores instance field private. * [ ] Make getScores()protected. * [ ] Make computeAverage()public. * [ ] Change getScores to return a copy of the scores list:(Solution: Student.java)public int[] getScores() { int[] sCopy = new int[scores.length]; for (int i=0; i < scores.length; i++) { sCopy[i] = scores[i]; } return sCopy; }
[1] https://docs.oracle.com/javase/tutorial/java/concepts/object.html