final

suggest change

final in Java can refer to variables, methods and classes. There are three simple rules:

Usages

Good Programming Practice

Some developers mark a variable final when it should not be reassigned.

final on a parameter means the method will not reassign that parameter. It does not stop the method from changing a mutable object's contents.

public int sumup(final List<Integer> ints);

This emphasizes that the sumup method is not going to change the ints.

Inner class Access

Before Java 8, a local variable used by an anonymous class had to be final. From Java 8, it must be effectively final: assigned once.

public IPrintName printName(){
  String name = "Ada";
  name = "Bea";
  return new IPrintName(){
      @Override
      public void printName(){
          System.out.println(name);
      }
  };
}

This does not compile. name is assigned twice, so it is not effectively final.

final static variable

Even though the code below is completely legal when final variable foo is not static, in case of static it will not compile:

class TestFinal {
    private final static List foo;

    public TestFinal() {
        foo = new ArrayList();
    }
}

The reason is, let’s repeat again, final variable cannot be reassigned. Since foo is static, it is shared among all instances of class TestFinal. When a new instance of a class TestFinal is created, its constructor is invoked and therefore foo gets reassigned which compiler does not allow. A correct way to initialize variable foo in this case is either:

class TestFinal {
    private static final List foo = new ArrayList();
    //..
}

or by using a static initializer:

class TestFinal {
    private static final List foo;
    static {
        foo = new ArrayList();
    }
    //..
}

final methods are useful when a base class implements behavior that a subclass must not change. They are not automatically faster. The JVM can devirtualize many non-final calls as well.

All wrapper classes in Java are final, such as Integer and Long. Callers cannot extend Integer and change its behavior. One requirement of an immutable class is that subclasses cannot override its methods. Declaring the class final is the simplest way to get that.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents