![]() |
VOOZH | about |
Access modifiers in Java are used to control the visibility of the variables, classes and methods within a class or package. There are different types of access modifiers that are used to define the accessibility in different ways. The access modifiers strictly enforce the level of accessibility and these are defined by different keywords.
Example: Access modifiers with interface and classes.
This is a public method. Method in the private interface. This is a private method. This is a protected method. This is a package-private method.
Explanation:
The public modifier provides the highest access among all the modifiers. We can access it anywhere in the package. The public modifier allows to use the variable, methods and class to acess in the same package.
Example: Demonstration of public access modifier in Java.
Hello Geeks
The protected modifier in Java allows the class, method and variable to Accessible within the same package and subclasses.
Example: Demonstrating the protected modifier in Java.
This is the protected method.
The private access modifier is used with method, class and variable and if the it can be only accessible in the class where it is defined.
Example: Demonstrating the private access modifier.
Private variable having message: Hello Geeks
When the modifier is not define then it automatically specified default method or package private. The default having the accessibility within the same package. If the the variable, method or class having no modifier then it considered as defualt modifier
Example: Demonstrating the default modifier in Java
This method having defualt modifier.
Modifier | Class | Interface |
|---|---|---|
public | Accessible from anywhere from different classes. | Similar to Class, accessible anywhere from different classes. |
default | It is only accessible within the same package. | Accessible within the same package. |
protected | Accessible within the same package and subclasses. | Not applicable to top-level interfaces. |
private | Accessible only in the class where it is defined | Not applicable to top-level interfaces and accessible in the same class or interface where it is defined. |