ITE “A” GROUP 2 ENCAPSULATION
What is encapsulation The binding or wrapping of data and codes into a single entity Thus the data gets hidden from being accessed directly from outside the class. All the members of a class are private by default, thus preventing them from being accessed from outside the class. This is similar to a capsule where several medicines are kept inside the capsule thus hiding them from being contaminated or directly consumed from outside.
Real life example of Encapsulation
Benefits and reasons of encapsulation Encapsulation is also useful in hiding the data or variables of a class from an illegal direct access. It provides your code - security, flexibility and its easy maintainability through encapsulation. NOTE: To achieve encapsulation in java, declare the variables of a class as private and provide public setter and getter methods to modify and view the variables values
Keywords in Encapsulation Class is a collection of object of the same kind and its also called an entity A method is a block of statements that has a name, performs the task of a class and can be executed by calling (also called invoking) it from some other place in your program. Object is used to reference a class. It is what actually runs in the program and can be a method, variable, data variable etc Setter is used to pass a variable or update the instance of a variable. Getter is used to print, retrieve or read value of a variable .
CODE package encapsulation.java; class A{ private int i; public void setI( int j) { i = j*j; } public int getI( ) { return i; } } public class EncapsulationJava { public static void main(String[] args) { A obj = new A(); obj.setI(5); int d=obj.getI(); System.out.println("Hey! she is "+d+"yrs now"); }