Showing posts with label package modifiers. Show all posts
Showing posts with label package modifiers. Show all posts

Tuesday, July 4, 2023

Difference between private, protected, public and package modifier or keyword in Java

In Java, access modifiers (or keywords) control the accessibility of classes, methods, and variables. There are four access modifiers in Java: private, protected, public, and the default (package-private) modifier. 

Here's an explanation of each: 

1. Private: Private access modifier restricts access to the member (class, method, or variable) only within the same class. It is the most restrictive access level. Private members cannot be accessed by other classes or even subclasses. This is commonly used to encapsulate internal implementation details and to enforce data hiding. 

Example:


public class MyClass {
    private int privateVariable;
    
    private void privateMethod() {
        // code here
    }
}

2. Protected: Protected access modifier allows access to the member within the same class, subclasses, and other classes in the same package. Subclasses that are outside the package can also access protected members using inheritance. Protected members are not accessible to classes in different packages unless they are subclasses. 

Example:


package mypackage;

public class MyClass {
    protected int protectedVariable;
    
    protected void protectedMethod() {
        // code here
    }
}

3.Public: Public access modifier allows access to the member from anywhere. Public members are accessible to all classes, both within the same package and in different packages. It provides the least restriction on accessibility. 

Example:


public class MyClass {
    public int publicVariable;
    
    public void publicMethod() {
        // code here
    }
}

4.Package (default): If no access modifier is specified, it is considered the default access level (also called package-private). Members with default access are accessible only within the same package. They are not accessible to classes in other packages, even if they are subclasses. 

Example:


package mypackage;

class MyClass {
    int packageVariable;
    
    void packageMethod() {
        // code here
    }
}

It's worth noting that access modifiers are hierarchical, meaning that each level includes the access levels below it. The hierarchy, from most restrictive to least restrictive, is: private, default (package-private), protected, and public.