DEV Community

Murali Rajendran
Murali Rajendran

Posted on

Access Modifier #public#private#protected#default

🌟 What is Access Modifier in Java?

1.Access modifiers control the visibility (or accessibility) of classes, methods, and variables in Java.
2.They define who can access what β€” inside or outside a class, package, or subclass.

  1. define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program
  2. Access modifiers control the visibility of classes, methods, and variables. Types: β€’ public:
  3. The public access modifier is specified using the keyword public.
  4. Public members are accessible from everywhere in the program.
  5. The member is accessible from any other class.
  6. Typical Use-Common for APIs or utility classes

class Vehicle {
public int speed; // public member
}

β€’ protected:
1.The member is accessible within its own package and by subclasses.
2.The protected access modifier is specified using the keyword protected.

  1. The methods or data members declared as protected are accessible within the same package or subclasses in different packages.

class Vehicle {
protected int speed; // protected member
}
β€’ default (no keyword): The member is accessible only within its own package.

  1. When no access modifier is specified for a class, method, or data member, it is said to have the default access modifier by default.
  2. This means only classes within the same package can access it.
  3. Members with default access cannot be accessed from classes in a different package.

β€’ private: The member is accessible only within its own class.

  1. The private access modifier is specified using the keyword private.
  2. The methods or data members declared as private are accessible only within the class in which they are declared.

class Person {

// private variable
private String name;

public void setName(String name)  {

    this.name = name; // accessible within class
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)