Default (Package-Private) Access Applied to an Instance Variable

When no access modifier exists in an instance variable declaration, the following default (package-private) access is granted:

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

Things to think about

  • Default access instance variables are generally considered to violate the principle of encapsulation. Use careful consideration before declaring a default access instance variable.


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;

import two.*;

class Tester { 

    public static void main(String args[]) {
        ClassOne co = new ClassOne();
        co.oneNumber = 111;
        co.displayOneNumber();

        //ClassTwo ct = new ClassTwo();
        //ct.twoNumber = 222;
        //ct.displayTwoNumber();
    }

}

class ClassOne {
        
    int oneNumber = 0;

    void displayOneNumber() {
        System.out.println("The value of oneNumber = " + oneNumber);
    }    
}

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


C:\Java\one>cd ..
C:\Java>md two
C:\Java>cd two
C:\Java\two>notepad ClassTwo.java

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


package two;

public class ClassTwo {
    
    int twoNumber = 0;

    public void displayTwoNumber() {
        System.out.println("The value of twoNumber = " + twoNumber);
    }     
}

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

Private instance variables are widely considered to be the norm. There are many occasions to use a default access instance variable as long as you are fully aware of the ramifications of doing so.


Tutorials