Java-Private Access Specifier

Private Access Specifier

Variables are generally declared with the access control modifier private. In such a case, they can be accessed only by methods of the class in which they are defined. This is the highest degree of protection. In the following program, the variable privateData can be accessed only by methods of the class setPrivateData( ) and showData( ).

Program

Program Source

class Data{
    
    int data;
    private int privateData;
    
    void setPrivateData(int data)
    {
        privateData = data;
    }
    
    void showData()
    {
        System.out.println("Data        : "+data);
        System.out.println("PrivateData : "+privateData);
    }
}

public class Javaapp {

    public static void main(String[] args) {
       
        Data d1  = new Data();
        d1.data = 50;
        d1.setPrivateData(100);
        d1.showData();
    }
}

Leave a Comment