We have seen the major access Java modifiers such as public, private, protected and default. But did you know that there are other modifiers in Java as well? They are:
- static
- final
- abstract
- transient
- synchronized
- volatile
Out of these, static, final and abstract are the most crucial and frequently used modifiers. Let us see the ‘Final’ and ‘static’ modifier in greater detail:
‘Final’ modifier:
Classes, methods and variables can have the keyword ‘Final’.
If a class is declared as ‘final’, it cannot be extended(or sub-classed)
If a method or variable is declared to be final, it cannot be ‘overridden'(‘Overriding is done to introduce new behavior in the sub-class in addition to the behavior of the super class)
Let us see a sample program:
Here when we try to modify the ‘final’ variable, it generates an error.
Similarly, an error is generated when we try to extend the ‘final’ class as well.
Here is the code, in case it is unavailable correctly on JDoodle:
final public class fin_example {
final int i=10;
void explain(){
i=i+1;
}
public static void main(String args[]) {
}
}
class example extends fin_example{
}
‘Static’ modifier:
Next, let us see the ‘static’ modifier.
The ‘static’ keyword can be applied to methods, variables and nested classes(not top level classes)
If a method is declared to be ‘static’, it can be called without the necessity to create an instance. The main() method is itself an example of a static method.
If a variable is declared to be ‘static’, it is shared all across the class with all methods. ‘Static’ variables are like global variables.
The ‘static’ modifier is mostly used when there is common data that has to be used across the entire class.
There are however several rules when working with ‘static’ modifiers. They are:
a. Static methods can only call other static methods
b. Static methods can only call other static variables
Here is a simple program that illustrates the ‘static’ modifiers with respect to methods and variables. The program generates an error since only static variables can be called inside a static method
We have seen the two non-access modifiers ‘final’ and ‘static’ in this post. We will see the other modifiers in the ‘M’ post later.
Join me as my Java journey continues tomorrow as well! 🙂
I’m participating in #BlogchatterA2Z by Blogchatter
It is quite informative Jayanthi!