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.
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 finalis 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.
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.
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.
This article is part of the series of articles to learn Java programming language from Tech Lead Academy:1. Introduction to programming
2. OS, File, and File System
3. Working with terminal
4. Welcome to Java Programming Language
5. Variables and Primitives in Java
6. Methods with Java
7. Java Math Operators and special operators
8. Conditional branching in Java
9. Switch statement in Java
10. Ternary operator in Java
11. Enum in Java
12. String class and its methods in Java
13. Loops in Java
14. Access modifiers in Java
15. Static keyword in Java
16. The final keyword in Java
17. Class and Object in Java
18. Object Oriented Programming in Java
19. OOP: Encapsulation in Java
20. Inheritance in Java
21. Abstraction in Java
22. Polymorphism in Java
23. Overriding vs Overloading in Java
24. OOP Design Principles in Java
25. Array in Java
26. Data Structures with Java
27. Collection framework in Java
28. ArrayList in Java
29. Set in Java
30. Map in Java
31. LocalDate in Java
32. Exception in Java
33. IO in Java
34. Design Patterns
35. Generics in Java
36. Multithreading in java
38. Big O Notation for coding interviews
39. Top 17 Java coding interview questions for SDET