monochrome photography of keys

Modifiers in Java

Access Modifiers

Access modifiers determine the extent to which a class or its members are visible to other classes, and they can modify both classes and individual members.

A class can be modified with public or package private (no explicit modifier). A class modified with public is visible to all classes everywhere, while a class without any explicit modifier is only visible to classes in the same package.

A member can be modified with public, protected, package private (no explicit modifier), or private.

  • A public member is visible from all classes everywhere.
  • A protected member is visible from classes in the same package.
  • A package private member is visible from classes in the same package, and from subclasses.
  • A private member is only visible within the class.

final keyword

final keyword can be used to modify a field, method or class.

  • A final field cannot be changed after an instance is constructed.
  • A final method cannot be overridden when extending the class.
  • A final class cannot be inherited by any other class.

final keyword is useful when creating an immutable class. An object is considered immutable if its state cannot change after it is instantiated. Immutability is preferred especially when the object can be used by concurrent multiple threads; because its state will not change, thread interference or data inconsistency will not occur.

To create an immutable class, we adhere to the following strategies:

  • Declare all fields as final and private.
  • Ensure that all methods cannot be overwritten. The simplest approach is to declare the class as final so that it cannot be inherited.

static keyword

static keyword can modify fields and methods in a class. Members declared as static belongs to the class, rather than individual instances.

synchronized and volatile keyword

synchronized keyword can modify a method or block, and it guarantees exclusive and consistent access to shared resources used in the modified method or block.

On the other hand, volatile keyword can modify a field and guarantees consistent access to the modified resource. It means that although it doesn’t provide exclusive access, any change to a volatile variable is visible to all other threads.