Which class is super class of every class

Variable declared private where variable can accessed

Answer :

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:

Variable declared private where variable can accessed

 

Leave a Reply

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