Java Reference
In-Depth Information
The above code establishes supertype-subtype relationship between three the interfaces
J
,
K
, and
L
, and the class
C
. Recall that an interface declaration defines a new type. Suppose that you have already declared three interfaces:
J
,
K
, and
L
. The three interface declarations define three types: type J, type
K
, and type
L
. The declaration of the class
C
defines a fourth type: type
C
. What is the relationship between the four types,
J
,
K
,
L
, and
C
? Class
C
is a subtype of
types
J
,
K
and
L
; type
J
is a supertype of type
C
; type
K
is a supertype of type
C
; and, type
L
is a supertype of type
C
. The
implication of this supertype-subtype relationship is that wherever a value of type
J
,
K
, or
L
is required, you can safely
substitute a value of type
C
. The following snippet code demonstrates this rule:
C cObject = new C();
// cObject is of type C. It can always be used where J, K or L type is expected.
J jobject = cObject; // OK
K kobject = cObject; // OK
L lobject = cObject; // OK
Interface Inheritance
An interface can inherit from another interface. Unlike a class, an interface can inherit from multiple interfaces.
Consider the
Singer
,
Writer
, and
Player
interfaces shown in Listing 17-23, Listing 17-24, and Listing 17-25.
Listing 17-23.
A Singer Interface
// Singer.java
package com.jdojo.interfaces;
public interface Singer {
void sing();
void setRate(double rate);
double getRate();
}
Listing 17-24.
A Writer Interface
// Writer.java
package com.jdojo.interfaces;
public interface Writer {
void write();
void setRate(double rate);
double getRate();
}
Listing 17-25.
A Player Interface
// Player.java
package com.jdojo.interfaces;
public interface Player {
void play();
void setRate(double rate);