Java Reference
In-Depth Information
of nothing but constants does not define a type, as a proper interface is expected
to do. And a class that “implements” such an interface isn't really implementing
anything - it is just using the constants in the interface (perhaps a uses keyword
would be more appropriate). Seeing the implements keyword should imply
that the class actually implements something.
For these reasons, the use of a class instead of an interface to define constants
is the recommended practice, accepting the need for the more verbose syntax to
refer to those constants. We note that J2SE 5.0, in fact, solves this problem with
the “static import” facility, which we explain in Chapter 5 after discussing the
import keyword.
Another interesting feature of interfaces is that an interface need not contain
either method declarations or data. It can be completely empty. Such an interface
can be useful as a “marker” of classes. That is, you can use the instanceof
operator to determine if a class is of the particular marker type, which then can
imply some quality of the class. One can use the empty Cloneable interface
to indicate whether a class overrides the clone() method from Object (see
Section 4.6.3) to make copies of instances of the class.
We discuss access rules and modifiers in the next chapter but here we note
that interface methods and constants are implicitly public . This means that
any class can access the methods and constants in the interface. The concrete
implementations of interface methods in classes that implement the interface
must also be public otherwise the compiler will complain.
4.6 More about classes
In this section we continue our introduction to the basics of class definitions and
objects with an examination of casting, the Object class, and the toString()
method.
4.6.1 Converting and casting object references
In Chapter 2 we discussed the topic of mixing different primitive types in the same
operation and the need in some cases to explicitly cast one type into another. The
same concepts apply when dealing with objects instead of primitives. Sometimes,
as with primitives, the type conversion is automatically handled by the compiler.
Consider a superclass Fruit with a subclass Pineapple :
class Fruit { ... }
class Pineapple extends Fruit { ... }
Let f be a variable of type Fruit and p be of type Pineapple . Then we can
assign the Pineapple reference to the Fruit variable:
Search WWH ::




Custom Search