Java Reference
In-Depth Information
((MyClass)ac).powerOnOff();
Since we cast the reference to type
MyClass
, we can call any of the methods defined in that class. We
can't get polymorphic behavior like this though. The compiler will determine the method that is called
when the code is compiled. To call the methods in the
RemoteControl
interface polymorphically, you
would have to have the reference stored as that type. Provided you know that the object is of a class
type that implements the
RemoteControl
interface, you can get from the reference store in the
variable
ac
to a reference of type
RemoteControl
. Like this for example:
if(ac instanceof RemoteControl)
((RemoteControl)ac).mute();
Even though the interfaces
RemoteControl
and
AbsoluteControl
are unrelated, you can cast the
reference 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.
Nesting Classes in an Interface Definition
You can put the definition of a class inside the definition of an interface. The class will be an inner class
to the interface. An inner class to an interface will be
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 would be 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 we have used in the illustration here.
The circumstances where you might define a class as an inner class to an interface would be when
objects of the inner class type have a strong logical association with the interface.
A class that implements the interface would have no direct connection with the inner class to the
interface - it would just need to implement the methods declared by the interface, but it is highly likely
it would make use of objects of the inner class type.