What are access modifiers in java explain with examples
In Java, access modifiers are keywords used to set the accessibility or visibility of classes, methods, variables, or constructors. They control the level of access that other classes have to these components.
There are four types of access modifiers in Java:
|Public||declarations are visible everywhere|
|Protected||declarations are visible within the package or all subclasses|
|Private||declarations are visible within the class only|
|Default||declarations are visible only within the package (package private)|
public: Members declared as
public are accessible from any class. They have the widest scope among all access modifiers.
protected: Members declared as
protected are accessible within the same package and subclasses, even if they are in different packages.
default (no modifier): Members with no explicit modifier (also known as package-private) are accessible within the same package but not from outside the package.
private: Members declared as
private are accessible only within the same class. They have the narrowest scope among all access modifiers.
In this example,
publicMethod() can be accessed from anywhere because they are declared as
protectedMethod() are accessible because they are in the same package.
defaultMethod() are accessible because they are in the same package and have default access.
privateMethod() are not accessible outside the
MyClass because they are private.