Interview Questions, Answers and Tutorials

Access modifiers

Access modifiers

Access modifiers in Java play a crucial role in controlling the visibility and accessibility of classes, methods, and variables within a program. Imagine you have a magical kingdom of code, and these access modifiers act as gates and keys, determining who can enter or interact with different parts of your kingdom.

There are four main types of access modifiers in Java: public, protected, default (package-private), and private. Let’s explore each one with simple examples.

  1. Public Access Modifier: The public access modifier is like a grand invitation to everyone. It allows unrestricted access to the class, method, or variable from any part of your code or even from outside.
public class Castle {
    public String treasure = "Gold and jewels";

    public void openGate() {
        System.out.println("The gate is open for everyone!");
    }
}

In this example, anyone in the kingdom can access the treasure variable and use the openGate method freely.

  1. Protected Access Modifier: The protected access modifier is like a semi-exclusive invitation. It allows access to the class, method, or variable within the same package and in subclasses.
public class Kingdom {
    protected String royalMessage = "Welcome to our kingdom!";

    protected void sendRoyalMessage() {
        System.out.println(royalMessage);
    }
}

Here, only classes within the same package or subclasses can use the royalMessage variable and call the sendRoyalMessage method.

  1. Default (Package-Private) Access Modifier: If you don’t specify any access modifier (i.e., no public, protected, or private), it becomes package-private. It means only classes within the same package can access the class, method, or variable.
class Forest {
    String wildlife = "Deer and rabbits";

    void observeWildlife() {
        System.out.println("Enjoying the beauty of nature!");
    }
}

Here, only classes in the same package (forest package) can access the wildlife variable and call the observeWildlife method.

  1. Private Access Modifier: The private access modifier is like a secret room inside the castle. Only the class that declares the variable or method can access it.
public class SecretChamber {
    private String secretMessage = "Hidden treasures";

    private void revealSecret() {
        System.out.println(secretMessage);
    }
}

In this case, only methods within the SecretChamber class can access the secretMessage variable and call the revealSecret method.

Access modifiers in Java help you control who can access different parts of your code. Just like a kingdom has public areas, restricted zones, and secret rooms, your Java code can have different levels of accessibility. Understanding and using access modifiers wisely can make your code more secure and organized.

Referrals: