Last Updated: 12 November, 2024 | 7 Mins Read
The final keyword is a non-access modifier used in Java programming to limit the use of variables, methods, and classes.
The final keyword is used with the following for different purposes:
In Java, when a variable is declared with the final keyword, it's known as a final variable, and its value can’t be changed once it's initialized with some value. If we change the value of the final variable then the compiler will throw an error at the compile-time of the program.
It is mandatory to initialize a final variable either during declaration or in the constructor, or in the respective block otherwise we will get a compilation error.
Let's have a look below at the implementation of the final variable with instances and the static variable.
Example 1 : Final variable in Java
class Candidate { // Final Instance Variable with assigned value final int age_limit = 18; // Blank final Instance Variables final String min_edu_general; // => Assigning value inside Constructor final String min_edu_reserved; // => Assigning value inside Instance Block // Static Final Variable with assigned value static final float app_fee_in_INR = 500; // Blank static final variable static final String exam_city; // => Assigning value inside Static Block // CONSTRUCTOR public Candidate() { min_edu_general = "GRADUATION"; } // INSTANCE BLOCK { min_edu_reserved = "INTERMEDIATE"; } // STATIC BLOCK static { exam_city = "BANGALORE/BENGALURU"; } } public class FinalVariableDemo { public static void main(String[] args) { // First printing static properties System.out.println("Application Fee (INR) : " + Candidate.app_fee_in_INR); System.out.println("Examination City : " + Candidate.exam_city); // Invalid in Java will get COMPILATION ERROR. // Candidate.application_fee_in_INR = 700; // Now, creating an object of the class and printing final instance variable Candidate object = new Candidate(); // Invalid in Java will get COMPILATION ERROR. // object.age_limit = 20; System.out.println("Age Limit : " + object.age_limit); System.out.println("Min Qualification (General) : " + object.min_edu_general); System.out.println("Min Qualification (RESERVED) : " + object.min_edu_reserved); } }
Output
Application Fee (INR) : 500.0
Examination City : BANGALORE/BENGALURU
Age Limit : 18
Min Qualification (General) : GRADUATION
Min Qualification (RESERVED) : INTERMEDIATE
In Java, a method declared with the final keyword is called the final method. A final method can't be overridden in subclasses. The JVM applies restrictions to the method.
Java has so many inbuilt classes, and some of the inbuilt classes contain final methods; these final methods we cannot override in the subclasses, for example, java.lang.Object class contains notify() and wait() methods as final methods.
Use Case: We must declare methods with the 'final' keyword if we are required to follow the same implementation throughout all the derived classes. By using the final method, we can apply the restriction on inheritance.
Example 2 : Final method in Java
class Parent { final void display() { System.out.println("Parent class display() method"); } } class Child extends Parent { // Will get compile time error if try to override final method // void display() {} } public class FinalMethodExample { public static void main(String[] args) { Child object = new Child(); object.display(); } }
Output
Parent class display() method
As its name suggests, a final class is declared using the final keyword. A final class cannot be inherited by subclasses. We can restrict the inheritance of classes by using the final class. During the compile-time, if compiler found any class is inheriting a final class, it will throw an error.
A final class must be a complete class; its functionality should meet the requirement. A final class never be an abstract class in Java.
Using the final classes, we can protect confidential information from unauthorized access. Suppose we have a non-final class that has some confidential data that must be accessed by only authorized people, but a hacker can inherit that non-final class in a subclass and steal confidential data or alter the business logic of the class. We can prevent this and provide security for important classes in the Java project. Therefore, we should always declare such classes with the 'final' keyword so that no one can inherit them.
There are some popular final classes provided by Java
All Wrapper Classes (such as Integer, Boolean, Character, etc.), String, StringBuffer, StringBuilder, System, Math, StrictMath, Formatter, Void, etc.
Example 3 : Final class in Java
final class LoginController { void login() { System.out.println("LoginController - login() method"); } } // We cannot extends final class // class Test extends LoginController {} public class FinalClassExample { public static void main(String[] args) { // Final classes are only called by their own object LoginController object = new LoginController(); object.login(); } }
Output
LoginController - login() method
Example 4 : The final class can extend another class in Java
For example, in Java, a final class can extend another class, whether that class is a normal class or an abstract class. Let's see the example below for better understanding:
class BaseController { void showCommonInfo() { System.out.println("BaseController - showCommonInfo()"); } } // A final class can extend another class final class CustomerController extends BaseController { void getCustomerPersonalInfo() { System.out.println("CustomerController - getCustomerPersonalInfo()"); } } public class FinalClassExample2 { public static void main(String[] args) { // Final class is only called by their own object CustomerController object = new CustomerController(); object.showCommonInfo(); object.getCustomerPersonalInfo(); } }
Output
BaseController - showCommonInfo()
CustomerController - getCustomerPersonalInfo()
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
What is a blank final variable in Java?
If we are not assigning a value at the time of declaring the final variable, that variable declaration is called a blank final variable or uninitialized final variable in Java. The Instance blank final variables can be initialized in the constructor or instance block. In the case of a static blank final variable, which will be initialized in the static block only.
Can we declare a final method as private in Java?
No, Private and 'final' keywords should not be used together with methods because it does not make any sense. Private methods of super classes are not inherited in subclasses, and they act like final methods.
What is the Final Reference Variable in Java?
When we use the 'final' keyword with a reference variable, it means we cannot reassign it to another reference or object. But we can change the value of members by using the setter methods. When we create a reference variable with a 'final' keyword, it means we cannot use the "=" operator to reassign it. If we try to reassign the value, it will throw a compile-time error.
Can we declare a final method with the static keyword?
No, As we know, we can't override a static method in subclasses. If we try to override a static method, then it is known as "method hiding." So, we should not make a static final method in Java. Both keywords do not create value together.
When should we use a final class in a Java?
1. Suppose we have a class that has some personal or secured information, and we want that class not to be extended by any other class. Then we should use the 'final' keyword with the class.
2. To create an immutable class, the 'final' keyword is mandatory. It means an immutable class is always a final class, like String.
Can we declare the abstract class as final?
No, there is no sense in declaring an abstract class as final. We will get a compile-time error because the final class cannot be extended by the child class, and the abstract class is only used by the child class to use and implement its abstract method.
Can a constant be defined using only the final keyword in Java?
Ans. A constant variable means the value of the variable cannot be changed throughout the program once assigned, and only one copy of it exists in the program.
In Java, we can create constants by declaring variables static and final.
Therefore, only the final keyword is not enough; we need static and final keywords both for making constants in Java.
Can a final variable be serialized in Java?
Yes, a final variable can be serialized in Java.
Can we modify the value of an interface field in Java?
No, we cannot modify the value of an interface field in Java. Interface fields are by default declared as final and static, which means that they are constants and cannot be changed after they have been initialized.
What will happen if we try to extend the final class in Java?
Ans. In Java, if we try to extend a final class, we will get a compile-time error because the final keyword is used to prevent a class from being subclassed.
A class's declaration as final indicates that its structure is complete and that inheritance cannot change it. This restriction is enforced by the compiler, which will throw an error if we attempt to extend a final class.
Why can't a constructor be final in Java?
Constructors cannot be declared as final in Java because constructors are not inherited and cannot be overridden, they cannot be specified as final in Java. The final keyword is used to prevent subclasses from overriding methods. Constructors, on the other hand, are not methods and so cannot be overridden.
Can we create an instance of the final class in another class?
Yes, we can create an instance of the final class in another class.
In Java, can we define the main method as final?
Yes, Java is allowed to define the main method as final.
In Java, can we mark a block as final?
No, it's not possible in Java; a block cannot be marked as final.
Can non-final local variables be used within a local inner class?
No. Within a local inner class, only final local variables can be used.