Learn Java Access Modifiers

Access Modifiers in Java with their Types and Examples of each:-


In Java, access modifiers are keywords used to control the visibility and accessibility of classes, fields, methods, and constructors. There are four main types of access modifiers: `public`, `protected`, `default` (also known as package-private), and `private`.

1. public: This modifier allows the member to be accessed from any class, whether it's in the same package or a different one.

Example:-
public class PublicExample {
    public int publicField = 42;

    public void publicMethod() {
        System.out.println("This method is public.");
    }
}


2. protected: Members with the `protected` modifier can be accessed within the same package and in subclasses (even if the subclass is in a different package).

Example:-
package mypackage;

public class ProtectedExample {
    protected int protectedField = 42;

    protected void protectedMethod() {
        System.out.println("This method is protected.");
    }
}

package mypackage;

public class Subclass extends ProtectedExample {
    void accessProtectedMember() {
        System.out.println("Protected field value: " + protectedField);
        protectedMethod();
    }
}


3. default (package-private): When no access modifier is specified, the member has "package-private" visibility. It's accessible only within the same package.

Example:-
package mypackage;

class DefaultExample {
    int defaultField = 42;

    void defaultMethod() {
        System.out.println("This method has package-private access.");
    }
}


4. private: Members marked as `private` are only accessible within the same class. They are not visible to any other class, even if they are in the same package.

Example:-
public class PrivateExample {
    private int privateField = 42;

    private void privateMethod() {
        System.out.println("This method is private.");
    }
    
    void accessPrivateMembers() {
        System.out.println("Private field value: " + privateField);
        privateMethod();
    }
}


Remember that these access modifiers help in enforcing encapsulation and controlling the visibility of various elements within your code. Choosing the appropriate access level for each member contributes to well-structured and maintainable code.

Post a Comment

0 Comments