What are the various access specifiers in Java

In Java, access specifiers (also known as access modifiers) are keywords that determine the visibility and accessibility of classes, methods, and variables. There are four main access specifiers in Java:

  • Public: The member is accessible from any other class.
  • Protected: The member is accessible within its own package and by subclasses.
  • Default (Package-Private): If no access specifier is specified, the member is accessible only within its own package.
  • Private: The member is accessible only within its own class.

Below is an example demonstrating the use of these access specifiers:

class Example { public int publicVariable = 1; protected int protectedVariable = 2; int defaultVariable = 3; // default access private int privateVariable = 4; public void display() { System.out.println("Public: " + publicVariable); System.out.println("Protected: " + protectedVariable); System.out.println("Default: " + defaultVariable); System.out.println("Private: " + privateVariable); } }

access specifiers Java public protected default private visibility accessibility