Java Reference
In-Depth Information
To reimplement a method of the
Object
class, you need to declare the method the same way as it has been
declared in the
Object
class, and then write your own code in its body. There are more rules to reimplement a
method. I will cover all rules in Chapter 16 on inheritance. You can reimplement the
toString()
method of the
Object
class in your class, say
Test
, as shown:
public class Test {
/* Reimplement the toString() method of the Object class */
public String toString() {
return "Here is a string";
}
}
I will discuss six methods of the
Object
class in detail in the sections to follow.
What Is the Class of an Object?
Every object in Java belongs to a class. You define a class in source code, which is compiled into a binary format
(usually a class file with the
.class
extension). Before a class is used at runtime, its binary representation is loaded into
JVM. Loading the binary representation of a class into JVM is handled by an object called a class loader. Typically,
multiple class loaders are used in a Java application to load different types of classes. A class loader is an instance
of the class
java.lang.ClassLoader
. Java lets you create your own class loader by extending the
ClassLoader
class.
Typically, you do not need to create your own class loaders. The Java runtime will use its built-in class loaders to load
your classes.
A class loader reads the binary format of the class definition into JVM. The binary class format may be loaded
from any accessible location, for example, a local file system, a network, a database, etc. Then, it creates an object of
the
java.lang.Class
class, which represents the binary representation of the class in JVM. Note the uppercase
C
in
the class name
java.lang.Class
. The binary format of a class definition may be loaded multiple times in the JVM by
different class loaders. A class inside a JVM is identified by the combination of its fully qualified name and its class
loader. Typically, the binary definition of a class is loaded only once in a JVM.
■
You can think of an object of the
Class
class as a runtime descriptor of the source code of a class. Your source
code for a class is represented by an object of the
Class
class at runtime.
Tip
The
getClass()
method of the
Object
class returns the reference of the
Class
object. Since the
getClass()
method is declared and implemented in the
Object
class, you can use this method on a reference variable of any type.
The following snippet of code shows how to get the reference of the
Class
object for a
Cat
object:
Cat c = new Cat();
Class catClass = c.getClass();
The
Class
class is generic and its formal type parameter is the name of the class that is represented by its object.
You can rewrite the above statement using generics, like so:
Class<Cat> catClass = c.getClass();