Home  >  Article  >  Java  >  Final Keyword in Java

Final Keyword in Java

WBOY
WBOYOriginal
2024-08-30 15:22:49636browse

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 Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. Variable: Declaring a variable as final restricts its modification to refer to any other value or reference.
  2. Methods: Declaring a method as final restricts method overriding of that method in the child classes.
  3. Classes: Declaring a class as final prevents the inheritance of that class.

According to good coding practices, these keywords are always recommended to be declared in capital letters.

Syntax of Final Keyword in Java

This keyword can be used in the below 3 ways:-

1. Variable

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 variable
Note-  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”);

2. Methods

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
}

3. Classes

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.
}

How Final Keyword Works in Java?

The final keyword helps to restrict the overriding of the classes, members or variables during inheritance.

1. Final Variables

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:

Final Keyword in Java

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-

  • Initialize at the time of declaration itself: We can easily declare a final variable at the time of declaring it. In case it is not initialized, then that variable is considered a blank final variable, and either of the next 2 ways can help us initialize a blank final variable.
  • Using instance-initializer block: Inside this block or the constructor, a blank final variable can be easily initialized. While using a constructor to initialize, always remember to initialize the particular variable in all the available constructors.
  • Static Block: One can also use a static block to initialize the blank final variable. Static block is always triggered once for each class; thus, the variable value whose values are not meant to be altered can easily be initialized using this block.

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:

Final Keyword in Java

2. Final Methods

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
}
}

3. Final Classes

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:-

  1. The first is to prevent the inheritance of that class. E.g., all the Wrapper classes present java.lang package is final classes; therefore, we cannot extend them in our classes but can use it by declaring their objects. Any attempt to access those classes will result in an error by the compiler.
final class myParentClass
{
// member variables and member functions
}
// illegal extend.
class myChildClass extends parentClass
{
// <--COMPILE-ERROR—> Can't subclass A
}
  1. The second use of final with classes is when one needs to create an immutable class, i.e. once the class’s object is created, we cannot change its content like the predefined String class. The class must be declared as final to make it immutable.

Note-

  • If a class is declared as final, then its member variables and member functions are also considered final by the compiler.
  • A class cannot be declared abstract where it depends on the child classes to complete its definition and final, which prevents the inheritance itself.

Examples of Final Keywords in Java

Below is the Different Example of Final Keyword in Java are:

1. Using Final Variable

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:

Final Keyword in Java

2. Using Final Methods

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:

Final Keyword in Java

3. Using Final Classes

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: 

Final Keyword in Java

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Protected Keyword in JavaNext article:Protected Keyword in Java