Private Access Applied to a Method

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

  • Full access is granted to invoke the method from within the same 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;

//class Tester extends ClassOne { // Inheritance
class Tester { 
   
    public static void main(String args[]) {
        new Tester().TesterMethod(); // Reference from within the same class
        //new Tester().methodOne(); // Inheritance from outside the class
        //new ClassOne().methodOne(); // Reference
    }

    private void TesterMethod() {
        System.out.println("Private method invoked from TesterMethod()");
    }
}

public class ClassOne { 

    private void methodOne() {
        System.out.println("Private method invoked from class ONE!");
    } 
}

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


C:\Java\one>ClassOne.java
C:\Java\one>java 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