Access Modifiers in Java
- Access Modifiers in Java helps to restrict the scope of a class, constructor, variable, method, or data member.
- We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
- There are four types of access modifiers available in Java:
- Public
- Protected
- Default - No keyword required
- Private
The scope of these access modifiers is shown as:
Public | Protected | Default | Private | |
---|---|---|---|---|
Same class | Yes | Yes | Yes | Yes |
Same package subclass | Yes | Yes | Yes | No |
Same package non-subclass | Yes | Yes | Yes | No |
Different package subclass | Yes | Yes | No | No |
Different package non-subclass | Yes | No | No | No |
Public
- The public access modifier is specified using the keyword public.
- The public access modifier has the widest scope among all other access modifiers.
- There is no restriction on the scope of public data members.
Protected
- 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.
Default
- When no access modifier is specified for a class, method, or data mebers, it said to be having the default access modifier by default.
- The data members, class or methods which are not declared using any access modifiers.
- The data members having default access modifier are accessible only within the same package.
Private
- The private access modifier is specified using the keyword private.
- The data members declared as private are accessible only within the class in which they are declared.
- Any other class of the same package will not be able to access these members.
Output :
The value of public variable in same class of a package is 25
The value of protected variable in same class of a package is 4
The value of default variable in same class of a package is 16
The value of private variable in same class of a package is 6
The value of public variable in subclass of same package is 25
The value of protected variable in subclass of same package is 4
The value of default variable in subclass of same package is 16
The value of public variable in other class of a package is 25
The value of protected variable in other class of a package is 4
The value of default variable in other class of a package is 16
The value of public variable outside package by subclass is 20
The value of protected variable outside package by subclass is 21
The value of public variable outside the package is 20
Comments
Post a Comment