Final keyword

Author: Ravi Poswal

Java uses the final keyword to limit the modification. It can be used to make variables, methods, and classes immutable once they have been defined. A value or action cannot be changed once it has been declared final.

  1. Variable

  2. Method

  3. Class

The final keyword can be used with variables. An empty final variable is referred to as an uninitialized final variable or blank final variable. Only in the constructor may it be initialized. It is also possible for the blank final variable to be static, which will only be initialized in the static block.

1. Variable

you cannot change the value of final variable(It will be constant).

Code Example

class Watch{   
final int timer=50;//final variable   
void run(){   
 timer=80;  
 }   
public static void main(String args[])
{   
Watch obj=new Watch();   
obj.run();   }  
}

2. Method

A subclass cannot override a final method. This guarantees that the way the method is implemented doesn't change. when a program compile then generate the compile time error

Code Example

class Bike {
    final void sound() {
        System.out.println("Bike 1");
    } 
}
class Vehicle extends Bike {
    void sound() {
        System.out.println("Vehicle ");
    } 
}
public class Test {
    public static void main(String[] args) {
        Vehicle d = new Vehicle();
        d.sound();
    }
}

3.Final Class

Another class cannot inherit a final class. This stops it from being extended by other classes. when a program compile then generate the compile time error i.e error: can not inherit from final Bike

Code Example

final class Bike{}
class Honda extends Bike{
void run()
{System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda=new Honda();
honda.run();
}}

FAQs

The final keyword in Java is used to restrict modification. It can be applied to variables, methods, and classes to prevent changes.

A final variable becomes a constant, meaning its value cannot be changed once it is assigned.

Yes, a final variable can be initialized later, but only once before it is used.

A final method is a method that cannot be overridden by subclasses.

We use final methods to prevent modification and ensure the original implementation remains unchanged.

A final class is a class that cannot be extended or inherited by other class

The String class in Java is a common example of a final class.

No, a final method cannot be overridden in Java.

No, a final class cannot be inherited.

Yes, it is a commonly asked topic in Java interviews and helps in understanding immutability and control over code behavior.

A concrete class in Java is a class that has complete implementation of all its methods and can be instantiated.

Yes, a concrete class can be declared as final in Java. but cannot be inherited