Access Modifiers in Java

Access Modifiers in Java 

Access modifiers are crucial Java tools that specify how variables, methods, and even the class itself can be accessed from other areas of the program.

Access modifiers in Java regulate which classes, methods, and variables are visible. In summary, these are the four primary types:
  • Public: Reachable from any location inside the project.
  • Private: Only accessible by members of the same class.
  • Protected: Accessible by subclasses and within the same package (even in distinct packages).
  • Default (no modifier): Also known as package-private, it is only accessible within the same package.

Access Modifiers for Java Classes

Access modifiers in Java regulate which classes, methods, and variables are visible. In summary, these are the four primary types:

public: Any other class in any package can access the class.
             ex: public class MyClass { }

default (no modifier): Only members of the same package can access the class.
                                        ex: class MyClass { }

Private: Top-level classes are not permitted. Private classes are limited to nested classes.
                ex: private class MyClass { } (nested only)

Protected: Top-level classes are not permitted. It is only possible to protect nested classes.
                    ex: protected class MyClass { } (nested only)

Access Modifiers for Variables (and Methods)

All four access modifiers can be used by variables and methods within a class. This regulates their visibility and modification by other classes.

Public: Reachable from any location, including other packages.
              ex: public int age;

Private: Only accessible by members of the same class.
                ex: private String name;

Protected: Available to subclasses in other packages as well as within the same package.
                    ex: protected double salary;

default (no modifier): Accessible only within the same package.
                                        ex: int id;

Comparison Table of Access Modifiers in Java
















Comments

Popular posts from this blog

Java Design Patterns

Application Programming Interface (API)