• Java Access Levels

    There are different type of access levels in java to control the visibility of classes, methods, and fields. For example, a class can only be seen and use if its inside of its own package or it is only visible to its subclasses. There are four levels of access in java. These are public, protected, private and no modifier. Below is the table of the access levels with its corresponding visibility that can also be found on Oracle Java Trails.

    Modifiers Class Package Subclass World
    Public Yes Yes Yes Yes
    Protected Yes Yes Yes No
    No Modifier Yes Yes No No
    Private Yes No No No

    In the table above, the Public modifier is visible and can be accessed by its own class, the package where it belongs, its subclasses and to world or simple, it can be accessed anywhere. A Protected modifier can be access in its own class, in its package, and its subclasses only. The No Modifier are methods, variables or class which has not given any modifier. It can only be accessed from its own class and package. The Private modifier is the most secured modifier because all the methods or fields that has a private modifier can only be accessed within its own class.

    Example

    In this example, we will be creating two classes named AccessLevels and ModifierTest which are in the same package.

    The AccessLevels Class:

    package com.javapointers.javacore;
    public AccessLevels {
         
         public void addNum1(int firstNum, int secondNum){
                System.out.println("The sum is: "+(firstNum+secondNum));
         }
         protected void addNum2(int firstNum, int secondNum){
                System.out.println("The sum is: "+(firstNum+secondNum));
         }
         void addNum3(int firstNum, int secondNum){
                System.out.println("The sum is: "+(firstNum+secondNum));
         }
         private void addNum4(int firstNum, int secondNum){
                System.out.println("The sum is: "+(firstNum+secondNum));
         }
    }

    The ModifierTest Class:

    package com.javapointers.javacore;
    public ModifierTest {
         
         public static void main(String args[]){
              AccessLevels access = new AccessLevels();
              access.addNum1(5, 10);
              access.addNum2(5, 10);
              access.addNum3(5, 10);
              access.addNum4(5, 10);  //This line will cause compile error.
         }
    }

    Explanation: In the above example, addNum1(), addNum2(), and addNum3() can be called in ModifierTest class because they have modifiers that can be accessed in its own package. Only addNum4() will cause error because of its modifier private. Remember that a private modifier can only be called inside its own class.

    Related Post