Java Reference
In-Depth Information
If you declare a class as final , you prevent any subclasses from being derived from it. To declare the
class PolyLine as final , you would define it as:
public final class PolyLine {
// Definition as before...
}
If you now attempt to define a class based on PolyLine you will get an error message from the compiler.
An abstract class cannot be declared as final since this would prevent the abstract methods in the class
from ever being defined. Declaring a class as final is a drastic step that prevents the functionality of the
class being extended by derivation, so you should be very sure that you want to do this.
Interfaces
In the classes that we derived from the class Animal , we had a common method, sound() , that was
implemented individually in each of the subclasses. The method signature was the same in each class, and the
method could be called polymorphically. The main point to defining the class Animal first, and then
subsequently the classes Dog , and Cat , and so on from it, was to be able to get polymorphic behavior. When
all you want is a set of one or more methods to be implemented in a number of different classes so that you
can call them polymorphically, you can dispense with the base class altogether.
You can achieve the same end result much more simply by using a Java facility called an interface . The
name indicates its primary use - specifying a set of methods that represent a particular class interface,
which can then be implemented appropriately in a number of different classes. All of the classes will
then share this common interface, and the methods in it can be called polymorphically. This is just one
aspect of what you can do using an interface. We will start by examining what an interface is from the
ground up, and then look at what we can do with it.
An interface is essentially a collection of related constants and/or abstract methods, and in most cases it
will contain just methods. An interface doesn't define what a method does. It just defines its form - its
name, its parameters, and its return type.
To make use of an interface, you implement the interface in a class - that is, you declare that the class
implements the interface and you write the code for each of the methods declared in the interface as
part of the class definition. When a class implements an interface, any constants that were defined in the
interface definition are available directly in the class, just as though they were inherited from a base
class. An interface can contain either constants, or abstract methods, or both.
Search WWH ::




Custom Search