Modifiers are keywords in Java that are used to change the meaning of a variable or method. In Java, modifiers are categorized into two types:
1. Access Modifiers
2. Non Access Modifiers
Access Modifiers
Access modifiers can be used to define access control for classes, methods and variables.
Types of Access Modifiers
publicprivatedefaultprotected
public: access modifiers is accessible everywhere. Example –
for class: public class Sample { }
for methods: public int add(a+b);
for variables: public int a;
private: access modifiers is accessible only within the class. Example –private int a = 100;
default: if we don’t specify any modifier then it is treated as default. Example –class Sample { }
protected: The protected access modifier is accessible only within package and outside of package through Inheritance. Example – protected class Sample { }
| Modifier | Within Class | Within Package | Outside of the package (through Inheritance) | Outside of the package |
private | Yes | No | No | No |
default | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public | Yes | Yes | Yes | Yes |
Non Access Modifiers
Non-access modifiers do not change the accessibility of variables and methods, but they do provide them special properties.
Types of Non Access Modifiers
staticfinalabstractsynchronizedVolatile
static: modifier is used to create class variable and class methods which can be accessed without instance of a class.
final: modifier for finalizing class, methods and variable i.e. it prevents its content from being modified. Final field must be initialized when it is declared. Example – final int a = 100;
abstract: modifier is used to create abstract classes and abstract methods.
synchronized and volatile modifiers, which are used for threads.
Next