Access Modifiers

Access modifiersare the keywords which controls the accessibility of classes, methods, fields or other members in a program.

Public

The public members are accessible everywhere.

Private

The private members are accessible only within their own class.

Protected

The protected members are accessible are accessible within the same class, subclasses, and within the same package. They are not accessible from outside the package if there is no inheritance relationship.

Default (Package-Private)

When no access modifier is specified (i.e., no public, private, or protected keyword), the member has "package-private" or "default" access. Members with default access are accessible only within the same package.

Some Special Modifiers in Java

In addition to access modifiers, java also has a few special modifiers:

  • Static (static): Used to declare class-level members (fields and methods) that belong to the class itself rather than to instances of the class.
  • Final (final): Used to make a member (field, method, or class) unchangeable or prevent method overriding (for methods) or class extension (for classes).
  • Abstract (abstract): Used with classes to declare abstract classes, which cannot be instantiated and may have abstract methods (methods without implementations). Abstract methods are meant to be implemented by subclasses.
  • Transitive (transient): Used with fields to indicate that they should not be serialized when an object is serialized. It is used for managing object persistence.
  • Volatile (volatile): Used with fields to indicate that they may be modified by multiple threads, ensuring proper synchronization when accessing the field.

Access modifiers play a vital role in encapsulation and maintaining the security and integrity of your Java code. They allow you to manage the accessibility of class members, controlling which parts of your classes can be accessed and modified. This practice is fundamental in adhering to sound object-oriented programming principles.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

What is the output when x = 5 in: if(x > 5) print A; else print B;

10 XP~3 min
Exercise 2 of 2Easy

The keyword used for alternative condition is ___.

10 XP~2 min