DEV Community

Hayes vincent
Hayes vincent

Posted on

Access Modifiers in Java

Access Modifiers

Java access modifiers are used to specify the scope of the variables, data members, methods, classes, or constructors These help to restrict and secure the access (or, level of access) of the data.

There are four different types of access modifiers in Java, we have listed them as follows:

-Default (No keyword required)
-Private
-Protected
-Public
Enter fullscreen mode Exit fullscreen mode

Default Access Modifier

Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.

Private Access Modifier

Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.

Protected Access Modifier

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Public Access Modifier

A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Referance:

https://www.tutorialspoint.com/java/java_access_modifiers.htm

Top comments (0)