The attributes (data) and the behaviours (code) are encapsulated in to a single entity/container or class Do not reveal the internals (fields) of the container to the external world External world can use and change the internals using the exposed handles or behavior or methods What is encapsulation?
Data Hiding Essential to ensure that the state is not altered accidentally without applying the applicable constraints and rules Make the data members private provide getters and setters Encapsulation in Java
Create a BankAccount class with a public double field balance with initial value of 100 Use a BankAccountTest class and from main method access this field to show the balance Now write a new method withdraw which reduces balance by input amount Now set the balance to 0 Withdraw 50 ? Now you have negative balance? Change the class and apply rules to ensure no negative balance. Use getters and setters Exercise