Java Reference
In-Depth Information
Notation:
The interface name and the
method names are italicized.
The dashed lines and hollow
triangles are used to point to
the interface.
«interface»
Edible
Animal
+
howToEat(): String
+
sound(): String
Fruit
Chicken
Tiger
Orange
Apple
F
IGURE
13.4
Edible
is a supertype for
Chicken
and
Fruit
.
Animal
is a supertype for
Chicken
and
Tiger
.
Fruit
is a supertype for
Orange
and
Apple
.
The
Fruit
class implements
Edible
. Since it does not implement the
howToEat
method,
Fruit
must be denoted as
abstract
(line 39). The concrete subclasses of
Fruit
must
implement the
howToEat
method. The
Apple
and
Orange
classes implement the
howToEat
method (lines 45, 52).
The
main
method creates an array with three objects for
Tiger
,
Chicken
, and
Apple
(line 3), and invokes the
howToEat
method if the element is edible (line 6) and the
sound
method if the element is an animal (line 9).
In essence, the
Edible
interface defines common behavior for edible objects. All edible
objects have the
howToEat
method.
common behavior
Note
Since all data fields are
public static final
and all methods are
public abstract
in an interface, Java allows these modifiers to be omitted. Therefore the following inter-
face definitions are equivalent:
omit modifiers
public interface
T {
public static final int
K =
1
;
public interface
T {
int
K =
1
;
Equivalent
public abstract void
p();
void
p();
}
}
13.13
Suppose
A
is an interface. Can you create an instance using
new A()
?
13.14
Suppose
A
is an interface. Can you declare a reference variable
x
with type
A
like this?
A x;
13.15
Which of the following is a correct interface?
✓
✓
Check
Point
interface
A {
void
print() { };
abstract interface
A
extends
I1, I2 {
abstract void
print() { };
}
}
(b)
(a)
abstract interface
A {
print();
}
interface
A {
void
print();
}
(c)
(d)
Search WWH ::
Custom Search