Java Reference
In-Depth Information
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable {
byte r, g, b;
public void setColor(byte rv, byte gv, byte bv) {
r = rv; g = gv; b = bv;
}
}
class Test {
public static void main(String[] args) {
Point p = new Point();
ColoredPoint cp = new ColoredPoint();
p = cp;
Colorable c = cp;
}
}
In this example:
• The local variable
p
of the method
main
of class
Test
has type
Point
and is ini-
tially assigned a reference to a new instance of class
Point
.
• The local variable
cp
similarly has as its type
ColoredPoint
, and is initially as-
signed a reference to a new instance of class
ColoredPoint
.
• The assignment of the value of
cp
to the variable
p
causes
p
to hold a referen-
ce to a
ColoredPoint
object. This is permitted because
ColoredPoint
is a subclass
type
Point
. A
ColoredPoint
object includes support for all the methods of a
Point
. In addition to its particular fields
r
,
g
, and
b
, it has the fields of class
Point
, namely
x
and
y
.
• The local variable
c
has as its type the interface type
Colorable
, so it can hold
a reference to any object whose class implements
Colorable
; specifically, it
can hold a reference to a
ColoredPoint
.
Note that an expression such as
new Colorable()
is not valid because it is not possible to
create an instance of an interface, only of a class. However, the expression
new Color-
that implements the
Colorable
interface.