Access modifiers
Access modifiers are used to set the accessibility of class, method, constructor and variable.
There are two types of modifiers in Java:
- access modifiers → private, default, protected and public
- non-access modifiers → abstract, static, final, volatile, transient etc.
Below are the four access modifiers:
private:
private variables and methods can be access within the same class only.
Note: In this above example, it is not allowed to use variable ‘a’ outside of Count class.
default:
The default access modifier uses with in the package. Default access modifier for class, methods and variable will be default if we explicitly don’t define.
protected:
protected variable or method can only be access inside the sub class or same package. In the below code ‘a’ will not be accessible if TestClass class not extends Count class.
public:
The public access modifier can be access from anywhere.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.