Protected Access Applied to a Method

When the protected access modifier is applied to a method, the following access is granted:

  • Full access is granted to invoke the method from within the same package. In addition, access is granted to invoke the method from subclasses of another package through inheritance only.

Things to think about

  • Be mindful of the class access type. A standard outer class can only have either public or default access.
  • A protected access method can be invoked (inheritance or reference) from within the same package irregardless of the class access.
  • A protected access method can only be invoked through inheritance outside of the package and only when it is contained in a public access class.


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 { // Inheritance package two
class Tester extends ClassOne { // Inheritance package one
    public static void main(String args[]) {
        new Tester().methodOne(); // Inheritance package one 
        new ClassOne().methodOne(); // Reference package one
        // new Tester().methodTwo(); // Inheritance package two
        // new ClassTwo().methodTwo(); // Reference package two
    }
}
class ClassOne {
    protected void methodOne() {
        System.out.println("Protected method invoked in package ONE!");
    } 
}

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 void methodTwo() { 
        System.out.println("Protected method invoked in package TWO!");
    }     
}

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


Tutorials