Java Reference
In-Depth Information
1.11.2. The
Object
Class
Classes that do not explicitly extend any other class implicitly extend the
Object
class. All objects are polymorphically of class
Object
, so
Object
is
the general-purpose type for references that can refer to objects of any
class:
Object oref = new Pixel();
oref = "Some String";
In this example,
oref
is correctly assigned references to
Pixel
and
String
objects even though those classes have no relationship except that both
have
Object
as a superclass. The
Object
class also defines several im-
1.11.3. Type Casting
The following code fragment seems quite reasonable (if not particularly
useful) but results in a compile-time error:
String name = "Petronius";
Object obj = name;
name = obj; // INVALID: won't compile
We declare and initialize a
String
reference which we then assign to a
general-purpose
Object
reference, and then we try to assign the refer-
ence to a
String
back to the
String
reference. Why doesn't this work?
The problem is that while a
String
is always an
Object
, an
Object
is not
necessarily a
String
, and even though you can see that in this case it
really is a
String
, the compiler is not so clever. To help the compiler you
have to tell it that the object referred to by
obj
is actually a
String
and
so can be assigned to
name
: