Modifier are keyword that are added to those definition to change their meaning.
Java has a two types of modifier,
I. Access Control Modifier.
II. Non-Access Modifier.
Access Control Modifier
Java provide access modifier to control access levels for classes, variable and constructor.
Default – It visible to the same package. No modifiers are need.
Public – It visible to the world.
Protected – It visible within the package and all sub classes.
Private – It visible within the classes only.
Non-Access Modifier
Java can provide some other modifier to provide rather than visibility . This modifier are called Non-Access Modifier. Each modifier have their own functionality .The most used non-access modifier listed below.
Final – Modifier to finalizing the implementations of classes, methods, and variables.
Static – Modifier to create class methods and variables .
Abstract – Modifier for creating abstract classes and methods .
Transient– Modifier is included in the statement that creates the variable, preceding the
class or data type of the variable.
Synchronized and Volatile -Modifiers for use in threads.
Example 1:class Phone { final int PRICE_MIN = 999; final int PRICE_MAX = 5600; //final variable final void display() //final method { System.out.println("Min Price is" + PRICE_MIN); System.out.println("Max Price is" + PRICE_MAX ); } }
Example 2:class Programming { public static void main(String[] args) { display(); } static void display() { System.out.println("I love to programming in Java."); } }
Java modifiers and access rules:
- If class A can’t access class B, then class A can’t access any member (method or variable) in class B.
- For a subclass outside the package, the protected member can be accessed only through inheritance.
- It is illegal to have even a single abstract method in a class that is not explicitly declared abstract!
- You can have an abstract class with no abstract methods.
- The first concrete subclass of an abstract class must implement all abstract methods of the super class.
- Initialization code block are not allowed in interfaces.
- Inner classes in interfaces must be public static.
- A member/(inner) interface can only be defined inside a top-level class or interface not inside methods.
- Static data fields can only be declared in static or top level types.