Understanding Final in Java - BunksAllowed

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

Community

demo-image

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.


1
2
3
4
5
public class A {
final int f = 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

1
2
3
4
5
6
7
8
9
10
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);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.


1
2
3
4
5
6
7
8
9
public class A {
int x = 10;
final void print() {
System.out.println(x);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

1
2
3
4
5
6
7
8
9
public class B extends A {
int y = 5;
//void print() {
// System.out.println(x + y);
//}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Final Class


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


1
2
3
4
5
6
7
8
9
final public class A {
int x = 10;
void print() {
System.out.println(x);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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


1
2
3
4
5
public class B extends A {
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

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