What are the differences between access modifiers and non-access modifiers in Java?
Access modifiers are the keywords which are used with classes, variables, methods, and constructors to control their access level.
There are four access modifiers in Java.
DefaultWhen no access modifier is specified, java is treated as a default modifier. The scope of the default modifier is limited to within the package.
PublicThe scope of public modifier is to access everywhere and even outside the package.
PrivateThe scope of private modifier is to access within the class itself.
ProtectedThe scope of the protected modifier is limited within the package and all subclasses.
Non-access modifiers are those keywords that do not have anything related to the level of access but they provide a special functionality when specified.
FinalFinal keyword can be used with variable, method or class. It prevents from its content from being modified. When declared with class, it prevents the class from being extended.
StaticThe static modifier is used with class variables and methods which can be accessed without an instance of a class. Static variables have only single storage. All objects share the single storage of static variable. They can be accessed directly without any object. Static methods can also be declared. the main() method is the popular static method. Static blocks can also be declared and are executed before main() method.
Abstractabstract can be used with class and methods. An abstract class can never be instantiated and its purpose is only to be extended. Abstract methods are declared without body and end with a semicolon. If a class contains an abstract method, it should also be specified as abstract. A class which extends an abstract class must implement all of its abstract methods.
SynchronizedIt indicates that the method can be accessed only by one thread at a time.
TransientAn instance variable is marked as transient to indicate the JVM to skip the particular variable when serializing the object containing it.
VolatileVolatile keyword is used to mark a java variable as "being stored in main memory". It means that every read of a volatile variable will be read from the computer's main memory and not from the CPU cache and writes to a volatile variable will be written to main memory and not just to the CPU cache.
StrictfpStrictfp keyword in java ensures that you will get the same result on every platform if you perform operations in the floating-point variable.
Published on 03-Jun-2019 14:01:42