Java Access Modifiers

Introduction

In this lesson of Java course, we will learn about Java access modifiers. Java Access Modifiers are an essential aspect of Java programming. They play a vital role in controlling access to Java classes, methods, and variables, providing an extra layer of security and encapsulation on Java programs. In this article, we will talk about what Java access modifiers are, the four different access modifiers in Java, and the recommended ways to use them.

1. What are Java Access Modifiers?

Java Access Modifiers are keywords used to specify the accessibility of classes, methods, and variables in Java. They define how a Java element can be accessed by other classes or objects. There are four types of Java access modifiers:

  1. Public
  2. Private
  3. Protected
  4. Package-private (default)
Java Access Modifiers

Each access modifier has its own specific function. Let’s explore these Java access modifiers in details.

2. Public Access Modifier

The public access modifier is the most permissive of all the access modifiers in Java. It allows a class, method, or variable to be accessed from anywhere in the program, whether it is in the same package or a different package. When we use the public access modifier, we make the class or method accessible to all other classes, regardless of their location.

We use the public access modifier when we want to make a class or method accessible to other parts of the program. For example, we might use a public access modifier for a method that needs to be accessed from multiple classes or packages.

//public class
public class Person {
    private String name;
    private int age;

    public Person(String name) {
        this.name = name;
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //public method
    public void displayPersonDetails(){
        System.out.println("My name is "+name+" I am "+age+" Years old");
    }
}

public class MainClass {
    
    public static void main(String[] args) {
        Person person = new Person("John", 40);
        person.displayPersonDetails();
    }
}

Output:

My name is John I am 40 Years old

Let’s look at some of the main point with our public access modifier

  1. We created a separate public class Person and a public method as displayPersonDetails().
  2. We created instance of the Person class in MainClass, this indicate that the Person class is accessible in other class.
  3. The public method displayPersonDetails() defined in the Person class is also accessible from the <code>MainClass class.

3. Private Access Modifier

The private access modifier restricts access of a class, method, or variable to the enclosing class only. This means that other parts of the program cannot access the member, even if they are in the same package or subclass. Private access modifier is typically used for methods and variables that should only be accessed by the class itself.

Here’s an example of a private access modifier being used in Java code:

public class Person {
    //private varilable
    private String name;
    private int age;
}

public class MainClass {

    public static void main(String[] args) {
        Person person = new Person();
        person.name="Test";
    }
}

In the above example, the both name and age member variables are defined as private. The person.name="Test" line in our MainClass will give the following compile time error:

Java access modifier

The above error showing that we are trying to access the private member variable outside the class, which is not supported for private access modifier.

We should use getter and setter to access these private variable. That is the only recommended way to allow access to these private variable from outside the class.
public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
Did you know, we can’t declare class or interface as private in Java, however for inner classes, we can declare them as private. Can you think why this

4. Protected Access Modifier

The protected access modifier allows access to a class, method, or variable to the enclosing class and any subclasses, as well as any other classes in the same package. This means that protected members can be accessed by other parts of the program, but only in certain circumstances.

Here’s an example of a protected access modifier being used in Java code:

public class MyClass {
    protected int myVariable = 10;

    protected void myMethod() {
        // method code here
    }
}

5. Package-Private (Default) Access Modifier

The package-private (default) access modifier allows access to a class, method, or variable to any other code in the same package. This means that members with package-private access can be accessed by other parts of the program that are in the same package, but not by any code outside of that package. Package-private access is typically used for methods and variables that should only be accessed by other parts of the program in the same package.

Here’s an example of a package-private access modifier being used in Java code:

class MyClass {
    int myVariable = 10;

    void myMethod() {
        // method code here
    }
}

6. High-level diagram outlining the different access types

ModifierAccess LevelSame ClassSame PackageSubclassOther Packages
publicHighestYYYY
protectedMedium-HighYYYN
package-privateMedium(default)YYNN
privateLowestYNNN

7. Best Practices for Using Java Access Modifiers

When working with Java access modifiers, it is important to keep in mind the following recommended approaches:

  • Use the most restrictive access level possible for each member to ensure encapsulation and protect sensitive data.
  • Use the public access modifier for methods and variables that need to be accessed by other parts of the program.
  • Use the private access modifier for methods and variables that should only be accessed by the class itself.
  • Use the protected access modifier for methods and variables that need to be accessed by subclasses or other classes in the same package.
  • Use the package-private access modifier for methods and variables that should only be accessed by other parts of the program in the same package.

Conclusion

In conclusion, Java access modifiers are an essential feature of Java programming that allows developers to control access to classes, methods, and variables. They are important for implementing encapsulation and protecting sensitive data. When developers follow recommended guidelines for access modifiers, they can write Java code that is both secure and easy to maintain. As always, the source code for this article is available on the GitHub.