Java Reference
In-Depth Information
Object
o
=
"string"
;
// Widening conversion from String
// to Object Later in the program...
String
s
=
(
String
)
o
;
// Narrowing conversion from Object
// to String
Arrays are objects and follow some conversion rules of their own. First, any array
can be converted to an
Object
value through a widening conversion. A narrowing
conversion with a cast can convert such an object value back to an array. Here's an
example:
// Widening conversion from array to Object
Object
o
=
new
int
[]
{
1
,
2
,
3
};
// Later in the program...
int
[]
a
=
(
int
[])
o
;
// Narrowing conversion back to array type
In addition to converting an array to an object, an array can be converted to another
type of array if the “base types” of the two arrays are reference types that can them‐
selves be converted. For example:
// Here is an array of strings.
String
[]
strings
=
new
String
[]
{
"hi"
,
"there"
};
// A widening conversion to CharSequence[] is allowed because String
// can be widened to CharSequence
CharSequence
[]
sequences
=
strings
;
// The narrowing conversion back to String[] requires a cast.
strings
=
(
String
[])
sequences
;
// This is an array of arrays of strings
String
[][]
s
=
new
String
[][]
{
strings
};
// It cannot be converted to CharSequence[] because String[] cannot be
// converted to CharSequence: the number of dimensions don't match
sequences
=
s
;
// This line will not compile
// s can be converted to Object or Object[], because all array types
// (including String[] and String[][]) can be converted to Object.
Object
[]
objects
=
s
;
Note that these array conversion rules apply only to arrays of objects and arrays of
arrays. An array of primitive type cannot be converted to any other array type, even
if the primitive base types can be converted:
// Can't convert int[] to double[] even though
// int can be widened to double
// This line causes a compilation error
double
[]
data
=
new
int
[]
{
1
,
2
,
3
};
// This line is legal, however, because int[] can be converted to Object
Object
[]
objects
=
new
int
[][]
{{
1
,
2
},{
3
,
4
}};
Modiier Summary
As we've seen, classes, interfaces, and their members can be declared with one or
more
modiiers
—keywords such as
public
,
static
, and
final
. Let's conclude this