In this post, I will help you understand more deeply about the final modifier in Java - how it affects your program. By understanding how the final modifier is used, you will have more flexibility in designing your programs.

 

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 PrettyCat

So 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



When a method is marked as final, it cannot be overridden. Let’s look at the following example:

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 Cat
So 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 PI
For 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:


About the Author:

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.



Add comment