Java Reference
In-Depth Information
Several of the classes in the Java API are declared final. For example, the
String class is final, so you cannot write a class that extends String.
The final keyword appears before the class keyword when declaring a final
class. For example:
public final class Hourly extends Employee
{
//Class definition...
}
A compiler error is generated if you try to write a class that subclasses
Hourly. The following class declaration will not compile:
public class PartTime extends Hourly
//error!
{
//Class definition...
}
You won't write final classes every day, but there are certain situations
where you might write a class that you do not want anyone to subclass.
For example, the designers of Java decided that no one should extend the
String class because it is such a fundamental class in the Java language.
If a class was allowed to extend String, this child class could override
the methods of String, changing the behaviors with undesired results.
By making String final, you can be assured that the implementation of
String objects is consistent and reliable.
final Methods
When a child class overrides a method in the parent class, the overridden
method is essentially hidden. The only way the parent method can be invoked
is if the child method explicitly invokes it. If you write a method with impor-
tant behavior that you do not want a child class to override, you can declare
the method final. A final method cannot be overridden by a child class.
The getClass(), wait(), and notify() methods of the Object class are
declared final. Their implementations are essential for the proper
behavior of an object, and these methods cannot be overridden by
any class.
Search WWH ::




Custom Search