Final Keyword in Java

We know that Java has 48 reserved keywords, one of which is the final keyword. It’s a Java keyword that can be used to limit the use of entities. It can be used for classes, methods, and variables. For various entities, the Java final keyword is used in multiple ways. The final keyword serves a different purpose for class, variable, and methods.

This article will discuss the final keyword in Java and explore how to implement and use it with different parameters.

In Java, what is the final keyword?

The final keyword in Java is a non-access specifier for restricting access to a class, variable, or function. If we use the final keyword to initialize a variable, we can’t change its value. When a method is declared final, it cannot be overridden by any subclasses. Furthermore, declaring a class final prevents other classes from inheriting or extending it.

In other words, no other classes can inherit the final classes.

That was a quick overview of Java’s final keyword. We’ll now look at using the final keyword in Java with variables, methods, and classes. We’ll go over the following points in depth:

  • final variable
  • final class
  • final method

The final variable in Java

We can’t change the value of a variable once we’ve declared it using the final keyword. We’ll get a compilation error if we try to change the value of the last variable. We can generally think of a final variable as a constant because its values cannot be modified.

What if we declare the reference variables final instead of the standard variables? The final reference variable’s constraint is that we can’t change “what the object refers to,” but we can change the object itself. It’s not possible to declare a variable final without first initializing it. While declaring a final variable, we must give it an initial value. If it is declared without initializing, the final variable is a final blank variable. However, initializing a final variable either during or after the declaration is required. We’ll get a compilation error if we leave it uninitialized.

Syntax of defining a final variable:

final int numVar = 35;                             //final variable
final float value;                                       //blank final variable
static final double rate = 7.5;             //final and static variable

Initialization of the final variable In Java

Because a final variable cannot be left uninitialized, the methods for initializing a final variable are as follows:

  • The most typical method is to declare a final variable and then initialize it. We refer to it as a final blank variable if you don’t initialize it while declaring it. The following two methods are used to create a final blank variable.
  • A final blank variable can be initialized either in an instance-initializer block or in the class’s constructor. If the class contains numerous constructors, you must initialize the final variable in each constructor; otherwise, an error will occur.
  • We can initialize a blank final static variable within a static block.

Code to illustrate the Java final Variable:

package com.codeunderscored.finalkeyword;
public class racingCode {
  //declaring and initializing a final variable
  final int speedlimit = 60;
  void controlSpeed() {
    //Trying to change the value of the final variable will give an error
    speedlimit = 150;
  }
  public static void main(String args[]) {
    Vehicle obj = new Vehicle();
    obj.controlSpeed();
  }
}

Code to illustrate the final blank variable:

package com.codeunderscored.finalkeyword;

public class StudentInfo {
  //Blank final variable
  final int id;

  //parameterized constructor
  StudentInfo(int idNum) {
    //Blank final variable must be initialized in constructor
    id = idNum;
  }

  void getDetails() {
    System.out.println("Id of the Employee is: " + id);
  }

  public static void main(String args[]) {
    StudentInfo stdInfo = new StudentInfo(36);
    stdInfo.getDetails();
  }
}

Code to illustrate how the final reference variable works:

package com.codeunderscored.finalkeyword;

public class FinalRefVariable {

  public static void main(String[] args) {
    // declaring a final reference variable builder
    final StringBuilder sb = new StringBuilder("Code");

    System.out.println(sb);

    // final reference variable constructor modifies the internal state of an object reference
    builder.append("code");

    System.out.println(sb);
  }
}

When is it OK to use a Java Final Variable?

The only difference between a regular and final variable is that we can modify the value of a standard variable after it has been assigned. Still, we cannot change the final variable’s value after being assigned. As a result, we must only use the final variables to set values that will remain constant during the program’s execution.

Java’s final method

We talked about the Final Keyword and how to declare the Final Variable before. By adding the Final keyword before the method name, we can declare Java methods as Final Methods. Subclasses cannot override the method using the Final Keyword. The Final Method’s purpose is to specify that a child or subclass that extends it cannot change the method’s definition.

Code responsible for expressing the final method in Java:

package com.codeunderscored.finalkeyword;
public class Parent {
  final void final_method() {
    //definition of the Final Method
  }
}
public class Child extends Parent {
  final void final_Method() // overriding the method from the parent class  
  {
    // another definition of the final method
  }
}

The Final Method creates a compile-time error in the example above. Because the Final method of the Parent class was overridden by the Final method of the Child class, this is not possible in the Java programming language.

Final methods’ purpose in Java

The goal of defining final methods is to prevent unintentional and incorrect use of method definitions while overriding the method. Though not theoretically erroneous, it can alter the meaning of the approach, causing the reader to misinterpret it. As a result, we declare methods as final in such cases to avoid unnecessary method declarations.

We create a Mammal class and add a non-final function called sound() to it. If someone builds a Human class and overrides the jump() method, causing the Human to print the incorrect jump, such as gallop. It will cause our method to be misused; thus, to avoid this, we’ll utilize the final method, as shown in the code below. To comprehend the final Method’s purpose, use the following code:

package com.codeunderscored.finalkeyword;

public class Mammal {

  final void features() {
    int legs = 4;
    int ears = 2;
    int eyes = 2;
    int tail = 1;
    System.out.println("The General Mammalia Characteristics are: ");
    System.out.println("Legs: " + legs);
    System.out.println("Eyes: " + eyes);
    System.out.println("Ears: " + ears);
    System.out.println("Tail: " + tail);
  }
}
public class Human extends Mammal {
  final void jump() {
    System.out.println();
    System.out.println("More humanly Characteristics:");
    System.out.println("Jump: Hop Skip");
  }
  public static void main(String[] args) {
    Human human = new Human();
    human.characteristics();
    human.jump ();
  }
}

Java’s Final Class

In Java, we may also declare a class with the final keyword. When a class is declared final, it prevents other classes from inheriting or extending it. In other words, a Java final class cannot be expanded by other inheritance classes. If another class tries to extend the final class, there will be a compilation issue.

The snippet of code for the final class:

final class Codeunderscored {
  // methods and variables of the class Tech
}

class coding extends Codeunderscored {
  // COMPILE- TIME error as it extends final class
}

To comprehend the final class, use the following code:

package com.codeunderscored.finalkeyword;

public class Coding extends Codeunderscored {
  void test() {
    System.out.println("My Method");
  }
  public static void main(String[] args {
    Coding code = new Coding();
    code.test();
  }
}
final class Codeunderscored {
  //code inside class
}

Example: Final variable

class Car{  
  final int speedlimit=180;//final variable  
  void run(){  
    speedlimit=400;  
  }  
  public static void main(String args[]){  
    Car cr=new  Car();  
    cr.run();  
  }  
}//end of class  

Example: Final method

class Car{  
  final void run(){System.out.println("running");}  
}  

class Benz extends Car{  
  void run(){System.out.println("safely running at100kmph");}  

  public static void main(String args[]){  
    Benz bz= new Benz();  
    bz.run();  
  }  
}

Example: Java final class

final class Car{}  

class Benz extends Car{  
  void run(){System.out.println("safely racing at 180kmph");}  

  public static void main(String args[]){  
    Benz bz= new Benz();  
    bz.run();  
  }  
}

Conclusion

We’ve concluded the article on Java’s final keyword. We discovered that the final keyword in Java could be used with variables, methods, and classes for various purposes. You can use the final keyword with variables, classes, and methods to restrict some things in exceptional circumstances. We also examined how to use a standard and a reference variable with a final keyword.

In addition, we learned how to prevent a class from overriding a method. A class can also be made final, preventing it from being extended by other classes. That is everything about Java’s final keyword.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *