![]() |
VOOZH | about |
Access modifiers in Java are used to control the visibility and accessibility of classes, methods, and variables. They help enforce encapsulation by restricting access to different parts of a program. Java provides four types of access modifiers to define scope and protection levels.
Real-World Example :In a banking app, private is used for balance (hidden), default for internal helpers, protected for methods used in subclasses, and public for actions like deposit or view details.
There are 4 types of access modifiers available in Java:
The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared.
Alice
Explanation: Direct access to name is not allowed outside Person, enforcing encapsulation.
If no access modifier is specified, the member has default (package-private) access and can only be accessed within the same package.This means only classes within the same package can access it.
Tesla
Explanation: Members with default access cannot be accessed from classes in a different package.
Geeks.java: Default class within the same package
GeeksNew.java: Default class from a different package (for contrast)
Explanation: In this example, the program will show the compile-time error when we try to access a default modifier class from a different package.
The protected access modifier is specified using the keyword protected. The methods or data members declared as protected are accessible within the same package or subclasses in different packages.
Access via subclass method: 100 0
Explanation: speed is accessible via subclass methods and other classes in the same package, but direct access from a different package (non-subclass) would fail.
The public access modifier is specified using the keyword public. Public members are accessible from everywhere in the program. There is no restriction on the scope of public data members.
15
Explanation: add() is globally accessible due to the public modifier.
Top-level classes or interfaces can not be declared as private because, private means "only visible within the enclosing class".