Skip to content

Java Access modifiers

In Java, access modifiers play a crucial role in determining who can access and modify classes, attributes, and methods. They provide a level of encapsulation and security, allowing us to design robust and maintainable code.

Exploring Each Access Modifier:

Public

  • Public access modifier allows unrestricted access to classes, attributes, and methods from any other class.
  • It's like throwing a grand party – everyone is invited, and anyone can join in!
java
   public class MyClass {
     public int myPublicAttribute;
     public void myPublicMethod() {
         // Method code
     }
   }

Private

  • Private access modifier restricts access to classes, attributes, and methods within the same class.
  • It's like having a secret hideout – only members of the club can access it!
java
   public class MyClass {
     private int myPrivateAttribute;
     private void myPrivateMethod() {
         // Method code
     }
   }

Protected

  • Protected access modifier allows access within the same package or by subclasses, even if they are in a different package.
  • It's like having a VIP section – only special guests (subclasses) and insiders (same package) can enter!
java
   public class MyClass {
     protected int myProtectedAttribute;
     protected void myProtectedMethod() {
         // Method code
     }
   }

Default (Package-Private)

  • Default access modifier (also known as package-private) restricts access to classes, attributes, and methods within the same package.
  • It's like having a neighborhood block party – only residents of the same neighborhood (package) are invited!
    java
    class MyClass {
      int myDefaultAttribute;
      void myDefaultMethod() {
          // Method code
      }
    }

Comparing Access Modifiers:

ModifierVisibilityExample
PublicAccessible from anywherepublic class MyClass { ... }
PrivateAccessible only within the same classprivate int myPrivateAttribute;
ProtectedAccessible within the same package or by subclassesprotected void myProtectedMethod() { ... }
DefaultAccessible within the same packageclass MyClass { ... }

Understanding Java access modifiers is essential for creating well-structured and secure code. By mastering these modifiers, you can control the visibility and accessibility of classes, attributes, and methods, ensuring the integrity and maintainability of your Java programs.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.