Java Reference
In-Depth Information
Chapter 7
The Object and Objects Classes
In this chapter, you will learn
About the hierarchical class structure in Java
Object class being the superclass of classes
About the
Object class with detailed examples
How to use methods of the
Object class in your class
How to reimplement methods of the
How to check two objects for equality
The difference between immutable and mutable objects
Objects class to deal with null values gracefully
How to use the utility methods of the
The Object Class
Java has an Object class in the java.lang package. All Java classes, those that are included in the Java class libraries
and those that you create, extend the Object class directly or indirectly. All Java classes are a subclass of the Object
class and the Object class is the superclass of all classes. Note that the Object class itself does not have a superclass.
Classes in Java are arranged in a tree-like hierarchical structure, where the Object class is at the root (or top).
I will discuss class hierarchy in detail in the chapter on inheritance. I will discuss some details of the Object class in
this chapter.
There are two important rules about the Object class. I will not explain the reasons behind these rules here. The
reasons why you could do these things with the Object class will be clear after you read the chapter on inheritance.
Rule #1
A reference variable of the Object class can hold a reference of an object of any class. As any reference variable can
store a null reference, so can a reference variable of the Object type. Consider the following declaration of a reference
variable obj of the Object type:
Object obj;
You can assign a reference of any object in Java to obj . All of the following statements are valid:
// Can assign the null reference
obj = null;
 
Search WWH ::




Custom Search