The final keyword can be used with variables, methods, and classes.
The final keyword is a special specifier that you can put together with variable, method, and class declarations.
- Final variable.
- Final method.
- Final class.
Final variable
Let’s start with the variables. Once we assigned a value for the final variable there is no way we can reassign it.
- Once a value is assigned we cannot change it.
- We use the final variable as constants in our code.
static final
is a common approach to create constant values in Java.
- final keyword can be used with local variables as well. The idea is the same cannot change the value.
- can be used with method arguments. Again cannot reassign the value of an argument.
Final method
If we declare our method as final, no child class can override it. Basically, we cannot override final methods.
- In the above example, we tried to override the final method and we are getting a compilation error.
Final class
if we declare our class as final, we cannot extend it. For example java.lang.String
class is final and we cannot extend it.
That’s all I have for the final keyword in Java.
Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming
OS, File, and File System
Working with terminal
Welcome to Java Programming Language
Variables and Primitives in Java
Convert String to numeric data type
Input from the terminal in Java
Methods with Java
Java Math Operators and special operators
Conditional branching in Java
Switch statement in Java
Ternary operator in Java
Enum in Java
String class and its methods in Java
Loops in Java
Access modifiers in Java
Static keyword in Java
The final keyword in Java
Class and Object in Java
Object-Oriented Programming in Java
OOP: Encapsulation in Java
OOP: Inheritance in Java
OOP: Abstraction in Java
OOP: Polymorphism in Java
The method Overriding vs Overloading in Java
Array in Java
Data Structures with Java
Collection framework in Java
ArrayList in Java
Set in Java
Map in Java
Date and Time in Java
Exception in Java
How to work with files in Java
Design Patterns
Generics in Java
Multithreading in java
Annotations in Java
Reflection in Java
Reflection & Annotations - The Powerful Combination
Run terminal commands from Java
Lambda in Java
Unit Testing in Java
Big O Notation for coding interviews
Top Java coding interview questions for SDET