Java Final


You use the final keyword to mark a variable constant, so that it can be assigned only once. So you must initialize a final variable with a value. If its not initialized (when declared, inside a constructor or inside static blocks), a compile-time error will occur.

Examples

1. PI is now a constant. Any attempt to reassign the value for PI will cause an error.

class MyClass { public static final double PI = 3.14; public static void main(String[] args){ System.out.println(PI); } }

2. If you make any method as final, you cannot override it.

class Bike{ final void run(){System.out.println("running");} } 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(); } }

The above code execution produces a compile-time error.

3. If you make any class as final, you cannot extend it.

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

The above code execution also produces a compile-time error.

More Information:

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.