- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In this Java article, you will learn how to use final keyword in Java with code example.
In Java, the final keyword can be applied to declaration of classes, methods and variables.
- Java final class: if a class is marked as final, it cannot be subclassed/inherited by another class. For example:
final class A { }
then the following code will not compile: class B extends A {} // compile error
- Java final method: when a method is final, that means it cannot be overriden, neither by methods in the same class or in sub class. For example:
class C {
final void foo() { }
}
the subclass D attempts to override the method foo(), but fail because foo() is marked as final: class D extends C {
void foo() { } // compile error
}
- Java final variable: if a variable is marked as final, its reference cannot be changed to refer to another object, once initialized. For example:
final String message = "HELLO";
Once the variable message is initialized and marked as final, the following code attempts to assign another value to it, will fails: message = "BONJOUR"; // compile error
Note: a class cannot be both abstract and final.
See all keywords in Java.
Related Topics:
Other Recommended Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on
Facebook and watch
his Java videos on YouTube.