Private Visibility

suggest change

private visibility allows a variable to only be accessed by its class. They are often used in conjunction with public getters and setters.

class SomeClass {
    private int variable;

    public int getVariable() {
        return variable;
    }

    public void setVariable(int variable) {
        this.variable = variable;
    }
}

public class SomeOtherClass {
    public static void main(String[] args) {
        SomeClass sc = new SomeClass();
        
        // These statement won't compile because SomeClass#variable is private:
        sc.variable = 7;
        System.out.println(sc.variable);

        // Instead, you should use the public getter and setter:
        sc.setVariable(7);
        System.out.println(sc.getVariable());
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents