Final Keyword in Java
The Final Keyword in Java allows declaring a class, data members, and methods to unalterable and behaves differently when it is used with classes, methods, and variables. In this article, we will briefly explain the final keyword in Java and how it is different from Finalize, and Finally.
After studying the super keyword in Java. Here’s another essential keyword in the concept of Inheritance in Java. The Final Keyword allows declaring a class, data members, and method to be unalterable. It’s generally used as an access modifier in Java for members. Let’s go through some of the examples of how we can implement final keyword in Java.
Contents
- What is a Final Keyword in Java?
- Uses of Final Keyword in Java
- Difference between Final, Finalize, and Finally in Java
- Conclusion
What is a Final Keyword in Java?
In Java, the final keyword can be used to indicate that something cannot be changed. It can be used in several contexts, such as to declare a variable as a constant, to declare a method as final, or to declare a class as final.
The final Keyword in Java behaves differently when used with classes, methods, and variables.
Points to remember about Final Keyword in Java:
Once any data member (a variable, method, or class) gets declared as final, it can only be assigned once.
- The final variable cannot be reinitialized with another value.
- A final method cannot be overridden by another method.
- A final class cannot be extended or inherited by another child class.
Best-suited Java courses for you
Learn Java with these high-rated online courses
Uses of Final Keyword in Java
Final Keyword in Java can be used with:
Variables with Final Keywords
When a final keyword is used with a variable, it makes the variable constant. Hence, once assigned, the value of the variable cannot be changed.
Let’s understand using an example.
public class MyClass { public static void main(String[] args) { final int num = 10; System.out.println(num); // prints 10
// the following line will cause an error because num is final num = 20; }}
Explanation:
In the above example, num is a final variable that is initialized with the value 10. If you try to change the value of num later in the code, you will get an error.
Must Check: Free Java Online Course and Certification
Correct Way to Implement Final Variable in Java
Example:
class Circle { public static void main(String[] args) { // Constant variable to store the value of pi static final double PI = 3.14;
// Radius of the circle int radius = 4;
// Calculate and display the area of the circle System.out.println("Area of circle: " + (PI * radius * radius)); }}
Output:
<strong>Area of circle: 50.24</strong>
Also, Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained
Methods With Final Keywords
The final keyword can also be used to declare a method as final. A final method cannot be overridden by a subclass.
Let’s understand it with an example.
Example:
public class MyClass { public final void myMethod() { // method implementation }}
In this example, myMethod is a final method that cannot be overridden by a subclass.
Here’s an example of how a subclass might attempt to override a final method:
public class MySubclass extends MyClass { // the following line will cause an error because myMethod is a final method public void myMethod() { // new implementation of myMethod }}
The subclass will not be able to override the myMethod method because it is declared as final in the superclass.
Declaring a method as final can be useful if you want to prevent subclasses from changing the behavior of the method. It can also improve the performance of the program because the Java virtual machine (JVM) can optimize the method since it knows that the method cannot be overridden.
Correct Way to Implement Final Methods in Java
Example:
class Animal { // Method to display the general characteristics of an animal final void displayCharacteristics() { // Constant variables to store the number of legs, ears, eyes, and whether the animal has a tail static final int NUM_LEGS = 4; static final int NUM_EARS = 2; static final int NUM_EYES = 2; static final int HAS_TAIL = 1;
System.out.println("General characteristics of an animal are: "); System.out.println("Legs: " + NUM_LEGS); System.out.println("Eyes: " + NUM_EYES); System.out.println("Ears: " + NUM_EARS); System.out.println("Tail: " + (HAS_TAIL == 1 ? "Yes" : "No")); }}
class Wolf extends Animal { // Method to display the additional characteristics of a wolf final void displayAdditionalCharacteristics() { System.out.println(); System.out.println("Additional characteristics:"); System.out.println("Sound: howl"); }
public static void main(String[] args) { Wolf w = new Wolf(); w.displayCharacteristics(); w.displayAdditionalCharacteristics(); }}
Output:
<strong>General characteristics of an animal are:Legs: 4Eyes: 2Ears: 2Tail: Yes
Additional characteristics:Sound: howl</strong>
Read More: Constructors in Java
Final Keyword with Classes
Classes followed by the final keyword in Java cannot be inherited by any subclass (or child class).
Let’s understand it with an example.
Example:
public final class MyClass { // class implementation}
In this example, MyClass is a final class that cannot be subclassed.
Here’s an example of how a class might attempt to subclass a final class:
public class MySubclass extends MyClass { // the following line will cause an error because MyClass is a final class}
The MySubclass class will not be able to extend the MyClass class because it is declared as final. Declaring a class as final can be useful if you want to prevent other classes from creating subclasses of the class.
Must Check: Java Online Course and Certification
Correct Way to Implement Final Class in Java
Example:
final class Day { // Constant variables to store the number of minutes and hours in a day static final int MINUTES_PER_DAY = 1440; static final int HOURS_PER_DAY = 24;
// Method to display the number of hours and minutes in a day static void displayHoursAndMinutes() { System.out.println("Number of hours in a day: " + HOURS_PER_DAY); System.out.println("Number of minutes in a day: " + MINUTES_PER_DAY); }}
class Main { // Main method public static void main(String[] args) { // Call the displayHoursAndMinutes method Day.displayHoursAndMinutes(); }}
Output:
<strong>Number of hours in a day: 24Number of minutes in a day: 1440</strong>
Read More: Java Operators Explained
Difference between Final, Finalize, and Finally in Java
Attributes | Final Keyword | Finally Block | Finalize Method |
---|---|---|---|
Definition | The final keyword is used as an access modifier to restrict alteration/changes on classes, variables, and methods. | Finally is a code block in Exception Handling in Java. This block carries the statements which get executed irrespective of exception occurrence. | Finalize is the method in Java that is used to perform memory clean-up before the object got collected by JVM garbage collection. |
Applicability | The final keyword is a concept of inheritance and it is used with the classes, methods, and variables. | The finally block comes with a try and catch block in exception handling. | finalize() method is used with the objects to clean the memory space. |
Functionality | The final variable cannot be reinitialized with another value. And a final method cannot be overridden by another method. Moreover, a final class cannot be extended or inherited by another child class. | Finally block runs the essential code irrespective of exception occurrence. | finalize method clean the object before its destruction. |
Execution | The final method only executes, when called. | Finally block is executed as soon as the try-catch block is executed. Its execution is not dependent on the exception. |
finalize method executes just before the object is destroyed by the JVM Garbage collector. |
Read More: Implementing Array in Java
Conclusion
Hope the above article helped you build an understanding of the final keyword in Java and its implementation ways. If you have any queries, feel free to reach out to us at the link below, and stay tuned for more java articles.
Read More: 8 Most Important Data Structures a Programmer Must Know
FAQs
What is Overriding in Java?
It's a condition where one data member or method gets shadowed (or overridden) by another data member or method with the same name is called overriding. Moreover, it occurs during runtime.
What is the Final Keyword in Java?
The final keyword is used as an access modifier to restrict alteration/changes on classes, variables, and methods.
Where can I use Final Keyword in Java?
Final Keyword with Variables: The final variable cannot be reinitialized with another value. Final Keyword with Methods: A final method cannot be overridden by another method. Final Keyword with Classes: A final class cannot be extended or inherited by another child class.
What is the major difference between Final, Finally, and Finalize in Java?
1. Final: The Final is a Keyword that allows declaring a class, data members, and method to be unalterable. 2. Finally: Finally is a code block in Exception Handling in Java. This block carries the statements which get executed irrespective of exception occurrence. 3. Finalize: Finalize is the method in Java that is used to perform memory clean-up before the object got collected by JVM garbage collection.
What is Final and Static Keyword in Java?
The Final Keyword allows declaring a class, data members, and method to be unalterable i.e. once the variable is assigned the value can't be changed while in static keyword the value is same for every instance.
What are the three different uses of final keyword in java?
Create Constants, prevent inheritance, and prevent methods from being inheritance are the three main uses of final keyword in java.
Can a constructor be a final keyword in Java.
No, constructor can't be a final keyword in Java.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio