More About final

Some Uses for the "final" Keyword in Java

Using "final" in a Method Header

public static void main(String [] args) {

        Dog d = new Dog(); );


public final void foo() {

      // code not shown


In the above example, since the method foo is declared final, it cannot be overriden in a class that derives from Dog. Doing so will result in a compiler error.

Using "final" in a Class Definition

public final class Foo {
// code not shown

In java, the use of the final keyword in the class header indicates that the class cannot be extended. In other words, no one will be allowed to create a new class that inherits from the final class.

In java, java.lang.String and java.lang.Math are examples of final classes.

Using "final" in a for-each Loop

for (final Dog d : pack) {

Here the coder is specifying that d should not be changed. However, using final here is unpopular because it leads to code noise or code clutter. Try to avoid using final for cases like these.

Controversy Over Use of "final"

Now that you know how to do it, try to avoid it unless there is a particular reason to be extra careful because indiscriminant use  causes code clutter.