Java Reference
In-Depth Information
if(ac instanceof RemoteControl)
((RemoteControl)ac).mute();
Even though the interfaces RemoteControl and AbsoluteControl are unrelated, you can cast the refer-
ence in ac to type RemoteControl . This is possible because the object that is referenced by ac is actually of
type MyClass , which happens to implement both interfaces and therefore incorporates both interface types.
If you got a bit lost in this last section don't worry about it. You won't need this level of knowledge about
interfaces very often.
Interface Types as Method Parameters
Of course, you can specify that a parameter to a method is of an interface type. This has a special signific-
ance in that a reference to an object of any type can be passed as an argument as long as the object type
implements the interface. By specifying a parameter as an interface type you are implying that the method
is interested only in the interface methods. As long as an object is of a type that implements those methods,
it is acceptable as an argument.
Methods within the standard class libraries often have parameters of interface types. The String ,
StringBuilder , and StringBuffer classes (plus the CharBuffer class that you see later in the topic)
implement the CharSequence interface. You'll see lots of class methods that have a parameter of type
CharSequence , in which case such methods will accept references to any of the class types I've mentioned
as arguments. For example, the StringBuilder and StringBuffer classes both have constructors with a
parameter of type CharSequence . You can therefore create new objects of these two class types from an
object of any class that implement the interface.
Nesting Classes in an Interface Definition
You can put the definition of a class inside the definition of an interface. The class is an inner class to the
interface. An inner class to an interface is static and public by default. The code structure would be like
this:
interface Port {
// Methods & Constants declared in the interface...
class Info {
// Definition of the class...
}
}
This declares the interface Port with an inner class Info . Objects of the inner class are of type
Port.Info . You might create one with a statement like this:
Port.Info info = new Port.Info();
The standard class library includes a number of interfaces with inner classes, including one with the name
Port (in the javax.sound.sampled package) that has an inner class with the name Info , although the Info
class does not have the default constructor that I have used in the illustration here. The circumstances where
Search WWH ::




Custom Search