Java Access Modifier Types
Table of Contents
Modifiers are keywords like public, private and protected that you add to those definitions to change their meanings. Java language has a two type variety of modifiers- Access Modifiers and Non-Access Modifiers, including the following −
1. Java Access Modifier Types
Access modifiers in Java helps to specified the scope of a class, constructor , variable , method or data member. There are four types of access modifier Types available in java :-
|Default – No keyword required
|If a variable or method is defined without any access modifier keyword, then that will have a default modifier access.
|Private access specifier can be used with an inner class, with method or with a variable. A private variable can be accessed within the class only. This variable won’t be available outside the class. So, the outside members cannot access the private members in which it is declared. Private modifier can not be used with top level classes. Note:-Classes and interfaces cannot be private.
|Protected access specifier can be used with an inner class, with method or with a variable. A protected member in super class can be accessed by all the classes within the same package and sub-class of any other packages. Note :- Protected access modifier cannot be used for class and interfaces.
|Classes, Methods or variables with public access modifiers can be accessed by all the other classes within same package as well as by all the classes in different packages.
2. Java Non Access Modifiers
The non-access modifiers are used to provides inheritance capabilities, synchronizing a method or block, whether all objects of our class share the same member value or have their own values of those members, whether a method can be overridden in a subclass, etc…
Modifiers can be found in the following table :-
|This keyword is used for memory management. It can be used with variables, blocks, methods and nested classes. It is used to share the same variable or method of a given class.
|Variable values can’t be changed once assigned, methods can’t be overriden, classes can’t be inherited.
|If applied to a method – has to be implemented in a subclass, if applied to a class – contains abstract methods
|Controls thread access to a block/method.
|This keyword is used to modify the value of variable by different threads and to make classes thread safe. This type of variable value is always stored and read in main memory.
|The member is skipped when serializing an object.
- What are the access modifiers in java?
- What are non-access modifiers in Java?
- How many types of Modifiers in Java?
- Can we declare a top-level class as private?
- Which access specifier can be used with a class?
- Can we declare a top-level class as protected?
- Which is the default access modifier?