Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Converting Objects and Simple Variables 129

Some objects do not require casting at all. You can use an object where any
of its superclasses are expected. All objects in Java are subclasses of the
Objectclass, so you can use any object as an argument when an Objectis
expected.


You also can use an object where one of its subclasses is expected.
However, because subclasses usually contain more information than their
superclasses, you might lose some of this information. If the object doesn’t
have a method that the subclass would contain, an error results if that
missing method is used in the program.


To use an object in place of one of its subclasses, you must cast it explicitly
with statements such as the following:


Graphics comp = new Graphics();
Graphics2D comp2D = (Graphics2D) comp;


This casts a Graphicsobject called compinto a Graphics2Dobject. You
don’t lose any information in the cast, but you gain all the methods and
variables the subclass defines.


Converting Simple Variables to Objects and


Back


One thingyou can’t do is cast an object to a simple variable or a simple
variable to an object. There are classes in Java for each of the simple vari-
able types include Boolean, Byte, Character, Double, Float, Integer,
Long, and Short. All these classes are capitalized because they are objects,
not simple variable types.


Using methods defined in each of these classes, you can create an object
using a variable’s value as an argument. The following statement creates
an Integerobject with the value 5309:


Integer suffix = new Integer(5309);


After you have created an object like this, you can use it like any other
object. When you want to use that value again as a simple variable, the
class has methods to perform that conversion. To get an intvalue from the
preceding suffixobject, the following statement could be used:


int newSuffix = suffix.intValue();


This statement causes the newSuffixvariable to have the value 5309,
expressed as an intvalue. One common casting from an object to a

Free download pdf