While looking for a new job, a few times I came across trivia style interview questions. Some of them meaningful, some pointless but I realized that I should know some of this stuff. In an effort to either learn the info long term or at least have a place to quickly get an answer I find coherent, I’ve decided to write my own answers as blog posts. First up, the “final” keyword in Java.

The “final” keyword in Java

What does the “final” keyword do? When should you use it?

The “final” keyword is an access modifier and does different things depending on where you use it. You can add “final” to classes, methods and variables. We’ll go through them one at a time. For the explanation, lets assume you’ve created an “animal” class.

First, the final keyword in Java makes a class unable to be sub-classed. Put simply, “final” prevents inheritance when applied to a class. So your dog class can’t inherit from your animal class if the animal class has “final” added to it’s header.

The “final” keyword makes a method unable to be overridden. Lets say that your animal class has a method called “age” that increments the age of the animal by 1 year and you don’t think any animals should be immune to the process of aging. To ensure that no one creates sub-classes of animal that age differently or don’t age at all, you’d add “final” to the method header of the “age” method.

The “final” keyword makes a variable assignable only once. Normally when writing code, you expect to be able to change the value of a variable whenever needed. Adding “final” to a variables declaration makes it so the variables value cannot be changed. Adding “final” essentially turns the variable into a constant. However, if your variable is an object then it’s attributes/properties can still be changed despite the fact that the instance of the variable itself cannot be changed. Let’s say that you want your dog class to have a constant called “numberOfLegs” with a value of 4. You’d make “numberOfLegs” final because you don’t want the number of legs to change. If it did, I don’t know if we could still call it a dog.

Why is it valuable?

As you might have guessed, the value of the “final” keyword is mostly in code wrangling. You’d use it when you want to add a bit more structure to the code you’re writing. You could do without it for small projects or simple scripts. It’s value comes out when you need to enforce strict behaviors on larger code bases.