The access level for a class member controls where it can be accessed.
One of the following four access level modifiers can be used for a class member:
Access levels for a class member can be listed from the most restrictive to the least restrictive as
The following table summarizes the four access levels for a class member.
Access Level for Class Member | Accessibility |
---|---|
private | Only within the same class |
package-level | In the same package |
protected | Same package or descendant in any package |
public | Everywhere |
The following is a sample class that declares many class members with different access levels:
public class Main { private int num1; // private access level int num2; // package-level access protected int num3; // protected access level public int num4; // public access level public static int count = 1; // public access level // m1() method has private access level private void m1() { // Code goes here } // m2() method has package-level access void m2() { // Code goes here } // m3() method has protected access level protected void m3() { // Code goes here } // m4() method has public access level public void m4() { // Code goes here } // doSomething() method has private access level private static void doSometing() { // Code goes here } }