How Java final modifier affect your code
- Details
- Written by Nam Ha Minh
- Last Updated on 17 August 2019   |   Print Email
1. Final Class in Java
When a class is marked as final, it cannot be subclassed. In other words, if we don’t want a class to be able to be extended by another class, mark it as final. Here’s an example:public final class PrettyCat { }If we try to extend this final class like this:
class MyCat extends PrettyCat { }Compile error: error: cannot inherit from final PrettyCatSo the final modifier is used to prevent a class from being inherited by others. Java has many final classes: String, System, Math, Integer, Boolean, Long, etc. NOTES:
- There is no final interface in Java, as the purpose of interface is to be implemented.
- We cannot have a class as both abstract and final, because the purpose of an abstract class is to be inherited.
2. Final Method in Java
public class Cat { public final void meow() { System.out.println("Meow Meow!"); } }Here, the meow() method is marked as final. If we attempt to override it in a subclass like this:
class BlackCat extends Cat { public void meow() { System.out.println("Gruh gruh!"); } }The Java compiler will issue a compile error: error:
meow() in BlackCat cannot override meow() in CatSo use the final keyword to modify a method in case we don’t want it to be overridden.
3. Final Variable in Java
When a variable is marked as final, it becomes a constant - meaning that the value it contains cannot be changed after declaration. Let’s see an example:final float PI = 3.14f;If we try to assign another value for this final variable later in the program like this:
PI = 3.1415f;The compiler will complain:
error: cannot assign a value to final variable PIFor reference variable:
final Cat myCat = new Cat();After this declaration, myCat cannot point to another object.In Java, constants are always declared with the static and final modifiers, for example:
static final float PI = 3.1415f;The final modifier can be also used in method’s arguments. For example:
void feed(final Cat theCat) { }This means code in the method cannot change the theCat variable.That’s all for the final modifier. I hope you have learned something new today.
Related Tutorials:
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 Java Access Modifiers
- Java Variables Passing Examples - Pass-by-value or Pass-by-reference?
- Understand Encapsulation in Java
Comments