Private Access Applied to an Instance Variable

When the private access modifier is applied to an instance variable, the following access is granted:

  • Full access is granted to read or change the value of the instance variable from within the same class.

Things to think about



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md one
C:\Java>cd one
C:\Java\one>Notepad ClassOne.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


package one;

// class Tester extends ClassOne { 
class Tester { 

    public static void main(String args[]) {
        ClassOne co = new ClassOne(); // test refereence
        //co.number = 111;

        //Tester t = new Tester(); // test inheritance
        //t.number = 111;

        // great - now use encapsulation
        //co.setNumber(111);
        //System.out.println("number = " + co.getNumber());

        //t.setNumber(444);
        //System.out.println("number = " + t.getNumber());

    }

}

class ClassOne {
        
    private int number = 0;

    void setNumber(int number) {
        this.number = number;
    }

    int getNumber() {
        return this.number;
    }
}

Now switch back to the command prompt (CMD) and type in the following commands.


C:\Java\one>cd ..
C:\Java>javac one\ClassOne.java
C:\Java>java one.Tester // play around with uncommenting and comment various statements.
Varying results


Final thoughts

There was no need to test the private modifier on a method outside of a package. The private modifier is irrelevant when it comes to packages.


Tutorials