Modifiers in Java
Modifiers in Java add or changes the meaning of the definition. Modifiers are further divided into two types
- Access modifier
- Non-access modifier
Access Modifiers in Java: Java supports four access modifiers namely public, private, default and protected.
- Public: The scope of the public is visible everywhere
- Private: Private is only visible within the class
- Default: It has scope only inside the same package.
- Protected: It has scope within the same package and all subclasses outside the packages.
Non-access modifiers: Non-access modifiers don’t change the accessibility of methods and variables but they provide some special properties. They are 5 types
Final, static, abstract, Synchronized and Volatile.
Final: Final can be used with variables, methods, or a class. If the final variable is final means that the variable will act like a constant. It means the final variables cannot be changed if once declared.
- Final methods cannot be overridden. It means child methods cannot override its parent method if the parent methods are final.
- If a class is final means that class cannot be extended. If a class is final means it cannot be extended.
The static modifier in Java
- Static modifiers can be used with variables and methods.
- Static variables are also known as class variables, they can be accessed without any object of that class. They will take only single storage, that means all the static variable will have the same instance of static variables. Static memory will get memory only once. They are initialized only once.
- Static methods don’t require an instance of a class. Example for static methods is the main methods, it is declared as static because the main method is called without creating an object.
- Static blocks are used to initialize static data members. The static block will execute before the main() method.
Abstract keyword in Java
The abstract is used with classes and methods. The abstract is not used with variables. The abstract is mainly used to achieve abstraction.