To achieve encapsulation in your beautiful Java code:
- Declare the variables of a class private
- Provide public setter and getter methods to modify and view the variables values.
So the code can go as follow:
/* File name : EncapTest.java */ public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } }
In order to avoid any other class to modify our encapsulated class, variables are declared as private and to get access, should be through its public getters and setters.
This is how we access:
/* File name : RunEncap.java */ public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()); } }
Benefits?
- Easy to model real-world entities
- Easy to maintain and understand
- Control how we access data and how is modified
- Reusability
- Flexibility
- Secure
This short video will help to clarify this concept. Enjoy!
No comments:
Post a Comment