In this post, we’re going to look at the different final keyword for java. It is a keyword used in java language to apply restrictions on its usage or modification by other classes or variables. Using this keyword, one tells the interpreter to not allow any future modification to that variable or method and treat it as constant. It can be used with the below 3 scenarios:-
ADVERTISEMENT Popular Course in this category FINANCIAL MODELING & VALUATION - Specialization | 51 Course Series | 30 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
According to good coding practices, these keywords are always recommended to be declared in capital letters.
This keyword can be used in the below 3 ways:-
Variables in java can be declared as variable to restrict any change to its values. It can be declared in any one of below three ways-
Syntax:
final int VAR1=21;//final variable final int VAR2; //blank final variable static final double DUMMY= 45.504;//final static variable static final double PK;//blank final static variableNote- Reference variables can also be declared static so that they can not hold a reference to another object. But due to the internal nature of the object, reference can be changed.
final String builder sb= new StringBuilder(“LetsLearn”);
The method declared with the final keyword is said to be the final method. The final method cannot be overridden by its child class, which means the child class method cannot change the definition of the final method present in the parent class. When we want the implementation of a method defined in parent class must be followed in all child classes, we must declare that method as final.
Syntax:
final int my1(){ //method defination }
Final keywords can also be used with classes to make it a final class, meaning the particular class cannot be extended or inherited by any other classes.
Syntax:
final class myClass{ /member variables and member functions. }
The final keyword helps to restrict the overriding of the classes, members or variables during inheritance.
Declaring a variable as final means restricting any alteration to the value of the variable in the inherited classes. A final variable can only be initialized once and must be used as it is; thus, one must initialize a final variable. It is mostly used with static to create a constant class variable.
For Example:
final int a =0;
We can also declare reference variables final also; in this case, one reference variable can not refer to different objects. But in java, the internal state of an object can be changed; the final reference variable refers to that. Thus we can make changes to the value of the reference variable. This is the same as using final arrays as shown below:-
Code:
class MyClass { public static void main(String args[]) { final int myarr[] = {1, 2, 3, 4, 5}; for (int q = 0; q < myarr.length; q++) { myarr [q] = myarr [q]*10; System.out.println(myarr [q]); } } }
Output:
Explanation
Here, array a1 refers to the same object; only the value of that object is changing because we all know that the arrays variable contains just the starting address of the memory location where those elements of the array are stored.
And in the same, if we try to refer to a different array using the same array variable a1, then the compiler will throw an error. Thus, using the word-final array here means any alteration can be made to the array member, but the variable is not allowed to refer to any other object.
Things to Remember
Initializing a final variable is necessary to prevent compile-time error. There is a difference between C++ const variables and these final variables that const variables need not be initialized. There are three ways to initialize a final variable-
Thus, the final keyword is used for those variables that need not change their value during the program’s execution. All the final variables created inside a method or block must be initialized there itself. Such type of variables is known as local final variables.
Explanation
In the below example, a variable I has been declared within the main function and initialised is considered a final local variable.
Code:
class myClass { public static void main(String args[]) { // local final variable final int i; i = 20; System.out.println(i); } }
Output:
A method declared as final can not be overridden in any of the subclasses, thus called a final method. The method needs to be declared as final if we require that the child classes follow the class’s same implementation.
Note- Final methods don’t need to be declared in the initial stage of inheritance(base class ). The method can be declared final in any subclass that we want further subclasses to follow the same definition.Code:
class A{ void myMethod(){ //method definition } } class B extends A{ final void myMethod(){ //overrides the method in parent class //runs successfully } } class C extends B{ void myMethod(){ //will throw error } }
Classes declared as final can not be inherited by any other classes. Mentioning a final keyword before the class name tells the compiler that this class’s definition can only be used as they are. No other classes can add their specifications to this definition or reuse its code. If one attempts to extend the final class, an error is thrown by the compiler indicating that this class is not meant to be extended. One can use final keywords in java in any for below 2 purposes:-
final class myParentClass { // member variables and member functions } // illegal extend. class myChildClass extends parentClass { // <--COMPILE-ERROR—> Can't subclass A }
Note-
Below is the Different Example of Final Keyword in Java are:
In the below example, different variables are initialized using various methods. For example- the SECOND variable is initialized using a constructor, whereas THIRD is initialized using an initializer.
Code:
class myClass { final int FIRST = 5; // a blank final variable final int SECOND; // another blank final variable final int THIRD; FIRST =10; //illegal attempt to change the value of final variable // a final static variable PI // direct initialize static final double MINVALUE = 3.141592653589793; // a blank final static variable static final double MAXRANGE; { THIRD = 25; // initializer block } static{ MAXRANGE = 200.3; } public myClass() { SECOND = -1;//needs to be initialised in every constructor } }
Output:
In the below example, abstract class myShape declares final methods getWidth and get eight those need not be overridden by the inherited classes. It also declares one abstract function whose implementation is mandatory in the subsequent classes. Thus the only the definition of an abstract function is implemented in a first child class and a second child class.
Code:
abstract class myShape { private double width; private double height; public myShape(double width, double height) { this.width = width; this.height = height; } public final double getWidth() //override not allowed { return width; } public final double getHeight() //override not allowed { return height; } abstract double getArea(); //needs to be defined in the child class } class firstChildClass extends myShape { public firstChildClass(double width, double height) { super(width, height); } final double getArea() { return this.getHeight() * this.getWidth(); } } class secondChildClass extends myShape { public secondChildClass(double side) { super(side, side); } final double getArea() { return this.getHeight() * this.getWidth(); } } public class myClass { public static void main(String[] args) { myShape s1 = new firstChildClass(10, 20); myShape s2 = new secondChildClass(10); System.out.println("width of s1 : "+ s1.getWidth()); System.out.println("height of s1 : "+ s1.getHeight()); System.out.println("width of s2 : "+ s2.getWidth()); System.out.println("height of s2 : "+ s2.getHeight()); System.out.println("area of s1 : "+ s1.getArea()); System.out.println("area of s2 : "+ s2.getArea()); } }
Output:
In the below program, we are using a final class Solid that defines a method to calculate the volume of a shape using its dimensions, but displaying the volume of a box is done using the inherited class’s printVol function. Shape As Solid is a final class; thus, class Shape will not be allowed to extend(or inherit) it. Thus, it uses Shape’s object to calculate the volume of any of Shape by just passing the arguments to the functions.
Code:
final class Solid { public double getVol(double length, double width, double height) { return length * width * height; } } class Shape { private float length; private float width; private float height; Shape(float length, float width, float height) { this.length = length; this.width = width; this.height = height; } public void printVol(Solid bObj) { double volume = bObj.getVol(this.length, this.width, this.height); System.out.println("Volume of the Shape: " + volume); } } public class myClass { public static void main(String[] args) { Solid bObj = new Solid(); Shape obj = new Shape(5, 4, 3); obj.printVol(bObj); } }
Output:
The final keyword is used to prevent the classes, variables, and methods to be overridden by its child classes. It can also be used to make classes immutable that is restricting the change in the value of their objects. The final keyword check is always checked at the compile time only. It is a great utility to prevent the reuse of the defined variables, logic, and classes.
The above is the detailed content of Final Keyword in Java. For more information, please follow other related articles on the PHP Chinese website!