Which class is super class of every class

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

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN

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

 

Explain Encapsulation principle

Leave a Reply

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