Protected Access Applied to an Instance Variable

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

  • Full access is granted to read or change or the value of the instance variable from within the same package. In addition, access is granted to read or change or the value of the instance variable from subclasses of another package through inheritance only.

Things to think about

  • Protected access instance variables are generally considered to violate the principle of encapsulation. Use careful consideration before declaring a protected 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 extends ClassTwo { 
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();

        //Tester t = new Tester();
        //t.twoNumber = 222;
        //t.displayTwoNumber();
    }

}

class ClassOne {
        
    protected 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 {
    
    protected 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 may be occasions to use a protected access instance variable as long as you are fully aware of the ramifications of doing so.


Tutorials