Modifiers in Java

In java, modifiers can be grouped into two categories:

  1. Access Modifiers
  2. Non-access Modifiers

Access Modifiers

Access modifiers deal with visibility. There are three access modifiers:

  1. public
  2. protected
  3. private

And four access levels :

  1. public
  2. protected
  3. private
  4. default (package-private)

Non Access Modifiers

  1. final
  2. abstract
  3. strictfp
  4. volatile
  5. transient
  6. synchronized
  7. native

Visibility for members and access modifiers

access modifiers java

Public

A class declaration with the public keyword gives all classes from all packages access to the public class. When a method or variable member is declared public, it means all other classes, regardless of the package they belong to, can access the member if the class itself is visible.

Private

Members marked private can't be accessed by code in any class other than the class in which the private member was declared.

Protected and Default Members

The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a a subclass even if the subclass is in a different package.

Final

The final keyword prevents a method from being overridden in a subclass. The final keyword on a class prevents the class from being inherited. A final variable cannot not be reinitialized.

Abstract

An abstract method is a method that's been declared but not implemented (The method contains no functional code or has no method body). Abstract classes must be inherited and cannot be instantiated.

Synchronized

The synchronized keyword indicates that a method can be accessed by only one thread at a time. A synchronized modifier can be applied only to methods - not variables, not classes, just methods.

Native

The native modifiers indicates that a method is implemented in platform-dependent code(C language mostly).

Strictfp

It applies to both classes and methods. With strictfp, you can predict how your floating points will behave regardless of the underlying platform the JVM is running on. It is related to the IEEE 754 standard.

Transient

If you mark an instance variable as transient, you're telling the JVM to skip this variable when you attempt to serialize the object containing it.

Volatile

The volatile modifier tells the JVM that a thread accessing the variable must always reconcile its own private copy of the variable with master copy in memory