Today we’ll understand the use of static and final keywords in Java. These two are important keywords of Java and are very significant.
The static keyword can be used with the variables, blocks, methods, imports and nested classes. A static variable is common to all objects of the class unlike normal variable. ‘static’ variables belong to the class and not to objects so they can be used directly from class name without the need of creating an object.
Here’s a small piece of code which further explains the ‘static’ concept:
//To access normal variables, we create object of the class A obj = new A(); System.out.println(obj.count); //static variables are accessed without a class object System.out.println(A.count);
static Methods are similar to static variables. static methods can only use static data members. They are common to all objects of the class and are accessed with the class name. One thing to note is that static methods can’t use ‘this’ and ‘super’ keywords.
If we make a variable final, it becomes a constant and its value can’t be changed. If the final variable is uninitialized, it can only be initialized in the constructor.
final int speedlimit = 90; speedlimit = 100; //ERROR
Since speedlimit is declared final, its value can’t be changed.
When a method is declared final, it can’t be overridden or redefined. When a class is declared final, it can’t be inherited. So final keyword is very useful when we need to declare constants, like PI (=3.14) is a constant and mustn’t be changed. If we have a concrete method which mustn’t be changed after Inheritance from some other class, we can declare it final. Finally, if we want to restrict a class from being inherited, we can declare it final.