Menu

Post image 1
Post image 2
1 / 2
0

Final Keyword in Java

DEV Community·PRIYA K·19 days ago
#gKvRqzo6
Reading 0:00
15s threshold

In Java, final means something cannot be changed further. It can be applied to variables, methods, and classes — but the effect is different in each case. 1. Final Variable A final variable can be assigned only once. After that, its value cannot change. class Demo { final int age = 20 ; void display () { // age = 25; // Error: cannot change final variable System . out . println ( age ); } } Enter fullscreen mode Exit fullscreen mode Why use it? When you want a constant value, like PI, fixed ID, etc. Example: final double PI = 3.14 ; Enter fullscreen mode Exit fullscreen mode 2. Final Method A final method cannot be overridden by a child class. class Parent { final void show () { System . out . println ( "Parent method" ); } } class Child extends Parent { // void show() { } // Error: cannot override final method } Enter fullscreen mode Exit fullscreen mode Why use it? To prevent subclasses from changing the original behavior of a method. 3. Final Class A final class cannot be inherited (extended).…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More