Java Final Keyword | Java Final Class | Java Final Variable and Method.

The Final in Java is a keyword that is applicable for only variables, methods, and class. The Java Final Keyword is used to restrict the user to use variables, methods, and class. The Final keyword is applicable for all the types of variables such as for instance variable, static variable, and local variable. Let's learn the Java Final Keyword in detail.

Final Keyword in java


1. Java Final Variable:

When a variable declared with Final Keyword, It is called Final Variable in Java. The value of the final variable can be assigned only once. Once the value of the final variable is assigned, you can't change the value of the variable. If you to do so then the compiler will give you a compile-time error. A variable declared as final and not initialized is called a blank final variable. We can initialize a blank final variable inside an initialization block or inside a constructor.



Example of Java Final Variable:


class FinalVariable{
	//final varible.
	final int num = 50;
	void display(){
		num = 100;
		System.out.println(num);
	}
	public static void main(String args[]){
		FinalVariable obj = new FinalVariable();
		obj.display();
	}
}


Output:

Compile Time Error.
cannot assign a value to final varible num.



2. Java Final Method:

When a method declared with Final Keyword, it is called Final method in Java. The Final method cannot be overridden by the child class. You might wish to make a method final if it has the implementation that should not be changed.

Example of Java Final Method:


class Parent{
	final void display(){
		System.out.println("Inside parent class method.");
	}
}
class Child extends Parent{
	//compile time error.
	//cannot overridden.
	void display(){
		System.out.println("Inside child class method.");
	}
	public static void main(String args[]){
		Child obj = new Child();
		obj.display();
	}
}


Output:

Compile Time Error.
display() in child cannot override display() in Parent.



3. Java Final Class:

When a class declared with Final Keyword, it is called Final class in Java. A class that is declared final cannot be extended. We can use the final class to prevent a class from being inherited



Example of Java Final Class:


final class Parent{
}
class Child extends Parent{
	void display(){
		System.out.println("Inside child class method.");
	}
	public static void main(String args[]){
		Child obj = new Child();
		obj.display();
	}
}


Output:

Compile Time Error:
cannot inherit from final Parent.




You may also like these posts:

Java Final Keyword | Java Final Class | Java Final Variable and Method. Java Final Keyword | Java Final Class | Java Final Variable and Method. Reviewed by Prashant Srivastava on December 25, 2019 Rating: 5

No comments:

Powered by Blogger.