Understanding Final in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Understanding Final in Java

Share This

The final keyword is used for many purposes. The different use of final keyword is shown with sample program below.


Final Variable


A final variable can not be updated. Generally, final variables are used where the values remain unchnaged throughout the application. For example, the value of Pi that does not change.


public class A { final int f = 0; }

public class Test { public static void main(String[] args) { A a = new A(); //a.f = 10; // final variable can not be assigned by any value after declaration System.out.println(a.f); } }

Final Method


Final methods can not be overwritten. Hence, if you define a method that can not be overwritten in sub-class, the method should be declared as final method.


public class A { int x = 10; final void print() { System.out.println(x); } }

public class B extends A { int y = 5; //void print() { // System.out.println(x + y); //} }

Final Class


If a class is declared as final, the class can not be inherited.


final public class A { int x = 10; void print() { System.out.println(x); } }

The following class will not compile, as the class B inherits class A, which is final.


public class B extends A { }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.