Explain Encapsulation principle

Explain Encapsulation principle

Answer : Object oriented programming (OOPS) supports three mechanisms which help us to implement object oriented model. They are encapsulation, inheritance, and polymorphism. As we see encapsulation is part of it. Below is principal of encapsulation:

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


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;




Your name: Java Honk
Your change name: Java Monk


Explain Encapsulation principle

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *