Java final keyword example
- 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:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
Quoting Nam:
Quoting Gopalakrishnan:
final void Test() {
}
public void Test(String str) {
}