Final Keyword in Java

 

What is the Final Keyword in Java? How to use Final Keyword – Java Tutorial

Solution:

The final keyword can be applied in three places in Java Program,

–>For declaring variables

–>For declaring the methods

–>For declaring the class

Video Tutorial – Final Keyword

The Final Keyword for variables

A variable can be declared as final.

If a particular variable is declared as final then it cannot be modified further.

The final variable is always a constant.

For example –  final int a = 10;

The Final Keyword for variable – Example Program

class Test 
{ 
	final int a =10;
	void fun() 
	{ 
		System.out.println("\n Hello, this function declared using final"); 
	} 
} 

class Test1 extends Test 
{ 
	int a = 20;
}

class finaldemo
{
	public static void main(String args[])
	{
		Test t = new Test1();
		t.fun();
	}
}

Output:

1 Error

Cannot override final variable a in-class Test1

The Final Keyword for Method

The final keyword can also be applied to the method. When a final keyword is applied to the method, the method overriding is avoided.

That means the methods that are declared with the keyword final cannot be overridden.

Consider the following Java program which makes use of the keyword final for declaring the method –

The Final Keyword for Method – Example

class Test 
{ 
	final void fun() 
	{ 
		System.out.println("\n Hello, this function declared using final"); 
	} 
} 
class Test1 extends Test 
{ 
	final void fun() 
	{ 	
		System.out.println("\n Hello, this another function"); 
	} 
}

class finaldemo
{
	public static void main(String args[])
	{
		Test t = new Test1();
		t.fun();
	}
}

Output:

1 Error

fun() in Test1 cannot override fun() in Test; overridden method is final final void fun()

The Final Keyword for Class declaration

If we declare a particular class as final, no class can be derived from it.

Following the Java program is an example of final classes.

The Final Keyword for Class declaration – Example

final class Test 
{ 
	void fun() 
	{ 
		System.out.println("\n Hello, this function in base class"); 
	} 
} 
class Test1 extends Test 
{ 
	final void fun() 
	{ 
		System.out.println("\n Hello, this another function"); 
	}
}

class finalclassdemo
{
	public static void main(String args[])
	{
		Test t = new Test1();
		t.fun();
	}
}

Output:

1 Error

 cannot inherit from final Test class Test1 extends Test

Summary:

In this article, we understood, What is the Final Keyword in Java? How to use Final Keyword in Java – Java Tutorial. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and the YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *