AppDividend
Latest Code Tutorials

Java Final Keyword Example | Final Keyword In Java

0

Final Keyword In Java | Java Final Keyword Example is today’s topic. Final is a keyword in java which is used to put a limit on the users (e.g., Prevents inheritance, Prevents Method Overriding, etc.).  A final variable can be explicitly initialized only once, and it is constant or fixed throughout the scope of the program. Example of the final keyword using the real scenario – a day has 24 hours, which is fixed.

#Key Points

  1. Final is a non-access modifier.
  2. Final is a keyword in Java to declare a constant variable.
  3. A final variable can be explicitly initialized only once.
  4. A final method cannot be overridden.
  5. A final method can be inherited.
  6. A final class cannot be inherited.
  7. All variables declared inside the interface are by default final.
  8. A constructor cannot be claimed as final.
  9. It is a better practice to name all the final variables in Capital Letters.

#Final Keyword In Java

A final keyword can be applied with variables also, a final variable that has no value it is called the final blank variable or uninitialized final variable. It can be initialized in a constructor only. The blank final variable can be static also, which will be initialized in a static block only. We will have a detailed learning of these. Let’s first learn the basics of the final keyword.

#Initialization of final variables

We must initialize a final variable. It can only be initialized once.

Initialization can be done by

  1. Initializer
  2. An allocation statement

Otherwise; the compiler will throw the compile-time error.

There are ways to initialize a final variable:

  1. The final variable can be initialized when it is declared. This final variable is called a blank final variable.
  2. The blank final variable can be initialized inside an instance-initializer block or constructor.
  3. The blank final static variable can be initialized inside a static block.

Let’s understand the above ways using the code given below.

//Java program to see different 
//Different ways of initializing a final variable 

class Initi
{ 
	final int number1 = 5;    // direct initialize 
	final int number2; 	// a blank final variable 
	static final double number3 = 5.16; 	//a final static variable number3 (direct initialize)
	static final double number4 ; 	  // a blank final static variable 
	
	// instance initializer block for
	{ 
		number2 = 25; 	// initializing number2
	} 

	// static initializer block for 

	static 
	{ 
		number4 = 7.3; 	// initializing number4 
	} 
		
    public static void main(String[] args)  
    { 
        Initi i= new Initi();
        System.out.println("Direct Initialize :"+i.number1);
        System.out.println("Blank Final Variable :"+i.number2);
        System.out.println("Final Static Variable :"+Initi.number3);
        System.out.println("Blank Static Variable :"+Initi.number4);
    }     
}

#Output

Also, you can try the code online to check the output.

 

Final Keyword In Java

In the above example, we have discussed different initialization frameworks to understand how final variables are defined, initialized, and executed.

Modes, where the final keyword is used.

Java Final Keyword Example

 

#Final Variable in Java

Its value cannot be changed during the scope of the program. It means that once a final keyword is initialized, we cannot change its value, and they are nothing but constants.

Let’s understand it using the code given below.

class Fv {  
   final int age=18;
   void Method() {  
      age=10;
      System.out.println("eligible to vote");
   }  
   public static void main(String args[]){  
      Fv obj = new Fv();  
      obj.Method();  
   }  
}

#Output

 

Final Variable in Java

Also, you can try online to check the output.

In the above example, we have tried to change the value of age which will generate a compile-time error as -“cannot assign a value to final variable age.”

which means that the final value cannot be changed; it can be initialized only once.

We can also use a blank final variable if we want to initialize value later.

For example: for assigning Roll numbers to the students which we cannot define in advance it is defined later according to the number of students; otherwise, all the students will have the same Roll numbers.

#Final Method

Final Methods cannot be overridden or reused.

Even if a subclass can call the final method of the parent class without any issue (means inheritance is possible) but it cannot override or replace it.

Let’s understand it using the code given below.

class FM {  
   final void b_tech() {
      System.out.println("b_tech Class Method");
   }  
}  
	     
class cse extends FM {  
   void b_tech(){
      System.out.println("cse Class Method");
   }  
	     
   public static void main(String args[]) {  
      cse obj= new cse();
      obj.b_tech();
   }
}

See the output.

Final Method

 

Also, you can try the code online to check the output.

In the above code, we can see that the subclass cannot be able to override the Parents class final method because the final keyword is used in the process of the parent class that shows that the final approach can be inherited but cannot be overridden. Which will give a compile time error – “b_tech() in “cse” cannot override the b_tech() in “FM.”

Let us see how the final method can be inherited using an example.

class FMI{  
   final void b_tech()
   {
      System.out.println("b_tech Class Method");
   }  
}  
	     
class cse1 extends FMI{  
   public static void main(String args[])
   {  
      cse1 obj= new cse1();  
      obj.b_tech();  
   }  
}

See the following output.

Final Method in Java Tutorial

 

Also, you can try the code online to check the output.

#Final Class

If you find a class definition is complete and you don’t want it to be sub-classed, declare it final.  A final class cannot be inherited; it also prevents the duplication of classes. It means that a class cannot be extended from another class, and if we extend a class from a final class it will throw a compile time error – “cannot inherit from the final class.”

Let’s understand it using the code given below.

final class FC{  
}  
	     
class FC1 extends FC{  
   void method(){
      System.out.println("My Method");
   }  
   public static void main(String args[]){  
      FC1 obj= new FC1(); 
      obj.method();
   }  
}

See the output below.

Final Keyword In Java | Java Final Keyword

 

In the above example we have seen an “FC1” or “Rextester” class cannot be inherited or extended from final class “FC”.it shows a compile-time error- “cannot inherit from final FC.”

Because a final class never has any subclasses, the methods of a final class are never overridden.

Finally, Java Final Keyword Example | Final Keyword In Java tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.