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.
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.
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.