In our previous post about java fields and methods, we learned what are those and their uses. Here, in this tutorial, we will learn what are the java access levels and how we can apply it to our fields and methods and what are their effects.
There are different types of java access levels to control the visibility of classes, methods, and fields. For example, you may want a class that can only be seen and used if it is inside of its own package or 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 |
The Public modifier is visible and can be accessed by its own class, the package where it belongs, its subclasses, and to world or in simpler terms, it can be accessed anywhere.
A Protected modifier can be accessed in its own class, in its package, and its subclasses only.
A No Modifier means that you haven’t added any modifiers and leave it as blank. 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 have a private modifier can only be accessed within its own class.
For our example, we will be creating two classes named AccessLevels and ModifierTest which are in the same package.
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)); } }
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. } }
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 an error because of its modifier private. Remember that a private modifier can only be called inside its own class.
This tutorial teaches us how we can limit access to our fields and methods with java access levels. In our next tutorial, we will learn a conditional statement using If, Else, and Else If.