The
| |||
The final classesYou will notice that a number of the classes in Java library are declaredfinal , e.g.
This means this class will not be subclassed, and informs
the compiler that it can perform certain optimizations it otherwise could
not. It also provides some benefit in regard to security and thread
safety.
The compiler will not let you subclass any class that is
declared final methodsYou can also declare that methods arefinal . A
method that is declared final cannot be overridden in a
subclass. The syntax is simple, just put the keyword final
after the access specifier and before the return type like this:
final fieldsYou may also declare fields to befinal . This
is not the same thing as declaring a method or class to be final .
When a field is declared final , it is a constant which will
not and cannot change. It can be set once (for instance when the object is
constructed, but it cannot be changed after that.) Attempts to change it
will generate either a compile-time error or an exception (depending on
how sneaky the attempt is).
Fields that are both
In the SlowCar class, the speedLimit
field is likely to be both final and static
though it's private .
final argumentsFinally, you can declare that method arguments arefinal .
This means that the method will not directly change them. Since all
arguments are passed by value, this isn't absolutely required, but it's
occasionally helpful.
What can be declared | |||
|