Java Reference
In-Depth Information
Determining the Class of an Object
Want to find out what an object's class is? Here's the way to do it for an object assigned
to the variable key :
String name = key.getClass().getName();
What does this do? The getClass() method is defined in the Object class and is, there-
fore, available for all objects. It returns a Class object that represents that object's class.
That object's getName() method returns a string holding the name of the class.
Another useful test is the instanceof operator, which has two operands: a reference to
an object on the left and a class name on the right. The expression produces a Boolean
value: true if the object is an instance of the named class or any of that class's sub-
classes or false otherwise, as in these examples:
boolean check1 = “Texas” instanceof String // true
Point pt = new Point(10, 10);
boolean check2 = pt instanceof String // false
The instanceof operator also can be used for interfaces. If an object implements an
interface, the instanceof operator returns true when this is tested.
Summary
Now that you have spent three days exploring how object-oriented programming is
implemented in Java, you're in a better position to decide how useful it can be in your
own programming.
If you are a “glass is half empty” person, object-oriented programming is a level of
abstraction that gets in the way of what you're trying to use a programming language for.
You learn more about why OOP is thoroughly ingrained in Java in the coming days.
If you are a “glass is half full” person, object-oriented programming is worth using
because of the benefits it offers: improved reliability, reusability, and maintenance.
Today, you learned how to deal with objects: creating them, reading and changing their
values, and calling their methods. You also learned how to cast objects from one class to
another, cast to and from primitive data types and classes, and take advantage of auto-
matic conversions through autoboxing and unboxing.
 
Search WWH ::




Custom Search