π 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.
- define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program
- Access modifiers control the visibility of classes, methods, and variables. Types: β’ public:
- The public access modifier is specified using the keyword public.
- Public members are accessible from everywhere in the program.
- The member is accessible from any other class.
- 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.
- 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.
- When no access modifier is specified for a class, method, or data member, it is said to have the default access modifier by default.
- This means only classes within the same package can access it.
- Members with default access cannot be accessed from classes in a different package.
β’ private: The member is accessible only within its own class.
- The private access modifier is specified using the keyword private.
- 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
}
Top comments (0)