Public Access Applied to a Method

When the public 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 or from any other package.

Things to think about

  • Be mindful of the class access type. A standard outer class can only have either public or default access.


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 {
    public void methodOne() {
        System.out.println("Public 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 {
    public void methodTwo() { 
        System.out.println("Public 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

None


Tutorials