What are the differences between access modifiers and non-access modifiers in Java?



Access Modifiers

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.

  • Default

    When no access modifier is specified, java is treated as a default modifier. The scope of the default modifier is limited to within the package.
  • Public

    The scope of public modifier is to access everywhere and even outside the package.
  • Private

    The scope of private modifier is to access within the class itself.
  • Protected

    The scope of the protected modifier is limited within the package and all subclasses.

Non-access Modifiers

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.

  • Final

    Final 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.
  • Static

    The 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.
  • Abstract

    abstract 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.
  • Synchronized

    It indicates that the method can be accessed only by one thread at a time.
  • Transient

    An instance variable is marked as transient to indicate the JVM to skip the particular variable when serializing the object containing it.
  • Volatile

    Volatile 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.
  • Strictfp

    Strictfp keyword in java ensures that you will get the same result on every platform if you perform operations in the floating-point variable.

Advertisements