What is data encapsulation
Answer : Data encapsulation is mechanism which binds code and the data together which it manipulates, and keeps both safe from outside interference and misusing. To restrict access of variable and method inside the class you could use three modifiers public, protected and private. Below table shows the access to members permitted by each modifier.
Access Levels
Modifier | Class | Package | Subclass | World |
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
Example:
package com.javahonk.encapsulationTest; public class EncapsulationTest { public static void main(String[] args) { EncapsulateData encapsulateData = new EncapsulateData(); // ERROR below line : The field encapsulateData.name is not visible //encapsulateData.name = "Changing your name"; // Only you can get name whatever set in the class System.out.println("Your name: " + encapsulateData.getName()); //We can change name because modifer is public encapsulateData.changeMyName = "Java Monk"; System.out.println("Your change name: " + encapsulateData.getChangeMyName()); } } class EncapsulateData { private String name = "Java Honk"; public String changeMyName = "Java Honk"; public String getName() { return name; } public String getChangeMyName() { return changeMyName; } }
Output:
Your name: Java Honk Your change name: Java Monk