Public modifiers
Public modifier is the direct opposite of the private access modifier. When you or I declare a class, method, or variable as public, we’re making it accessible from any other class in the program—no restrictions at all. Think of it like a public school where anyone can apply and get in. In the same way, anything marked as public can be freely accessed and used across the entire application. As developers, using public modifiers gives us flexibility, especially when we want certain parts of our code to be open for interaction.
Public: When we declare a class with the “public” modifier, it becomes visible in various scenarios:
It is visible within the same class where it is defined.
It is also visible in any subclass that belongs to the same package as the class.
Additionally, it is visible in any non-subclass (a regular class) within the same package.
Furthermore, it remains visible in any subclass even if it belongs to a different package.
Lastly, it is visible in any non-subclass, even if it belongs to a different package.
Remember, the “public” access modifier allows a class to be accessed from anywhere, making it more widely accessible. On the other hand, the “default” access modifier restricts access to within the same package only.
