Chapter 7. Working with Objects and Classes
In the previous two chapters, we came to know Java objects and then
their interrelationships. We have now climbed the scaffolding of the
Java class hierarchy and reached the top. In this chapter,
we’ll talk about the Object class itself,
which is the “grandmother” of all classes in Java.
We’ll also describe the even more fundamental
Class class (the class named “Class”)
that represents Java classes in the Java virtual machine. We’ll
discuss what you can do with these objects in their own right.
Finally, this will lead us to a more general topic: the reflection
interface, which lets a Java program inspect and interact with
(possibly unknown) objects on the fly.
The Object Class
java.lang.Object is
the ancestor of all objects; it’s the primordial class from
which all other classes are ultimately derived.
Methods defined in
Object are therefore very important because they
appear in every instance of any class, throughout all of Java. At
last count, there were nine public methods in
Object. Five of these are versions of
wait( ) and notify( ) that are
used to synchronize threads on object instances, as we’ll
discuss in Chapter 8. The remaining four methods
are used for basic comparison, conversion, and administration.
Every
object has a toString( ) method that is called
implicitly when it’s to be represented as a text value.
PrintStream objects use toString( ) to print data, as discussed in Chapter 10. toString( ) is also used when an object ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access