Variable declared private where variable can accessed

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

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:

Variable declared private where variable can accessed

 

Leave a Reply

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