final

Summary

The final modifier is used to declare variables as always retaining the same value or reference. When used on classes, the class cannot be subclassed.

Syntax

final statement

Parameters

statement
The statement to make 'final'.

Description

The final keyword operates differently depending on the context it is used.

When applied to a variable declaration, the variable must be initialized. The initialized value or reference is the "final" value/reference for the variable. It cannot be modified further, and properties cannot be added to or deleted from the variable. For primitive types, the final keyword will create a constant. For reference types, the object that is being referenced by the variable cannot be changed.

1
2
final int x = 100;
// x = 102; // error

Although a const keyword is reserved by the language, it is not used. This is by design. If a variable is initialized to an object reference, the object can still be modified (e.g. via other references to the same object). Thus, this creates a false sense of security and can be a source for confusion; in order to encourage the highest code quality, these factors had to be minimized. Therefore, final was used instead of const. "Constants" can still be created by using the final modifier on variable declarations with a primitive type.

When the final modifier is applied to a class, the class cannot be subclassed.

1
2
3
4
5
6
final class Foo
{
}
/*
class Bar : Foo {} // error
*/

If the final modifier is applied to an implementation of an abstract class method, a virtual method, or interface method, the method will no longer be overridable by further subclasses. Essentially, the final modifier, when applied to methods, acts similarly to override but prohibits future subclasses from further overriding the method.

1
2
3
4
5
6
7
8
9
10
11
12
interface IFoo
{
    void bar();
}
class Foo : IFoo
{
    final void bar() {}
}
class Baz : Foo
{
    // override void bar() {} // error
}

When applied to class fields, the field does not need to be initialized. Instead, the final field can be initialized in the constructor. For instance fields, the field must be initialized in an instant constructor; for static fields, the field must be initialized in a static constructor. If the constructor is overloaded, the field must be initialized in all overloads.

Examples

Final Variable Declaration
1
2
final int x = 100;
final int y = x + 1;
Final Field
1
2
3
4
class Foo
{
    final int bar = 1;
}
Final Field, Initialized in Constructor
1
2
3
4
5
6
7
8
9
class Foo
{
    final int bar;
     
    public Foo()
    {
        bar = 1;
    }
}
Final Class
1
2
3
4
5
6
final class Foo
{
}
/*
class Bar : Foo {} // Error
*/
Final Method
1
2
3
4
5
6
7
8
9
10
11
12
interface IFoo
{
    void bar();
}
class Foo : IFoo
{
    final void bar() {}
}
class Baz : Foo
{
    // override void bar() {} // error
}

See Also

Share

HTML | BBCode | Direct Link