java.lang.Object

We'll finish this chapter by describing a couple of much-used classes that we have seen informally already: Object and String.

The class java.lang.Object is the ultimate parent of every other class in the system, and it has half-a-dozen methods which therefore can be invoked on any and all objects. (An object is able to invoke the methods in all its parent classes — remember how ClockView objects could call setVisible() because they got it from their parent JFrame). Following are some of the members Object has. You can skim through this now, jumping ahead to the description of type String, and return if you need more information about something specific in Object.

public class Object {
     public java.lang.Object();  // constructor

     public java.lang.String toString();

     public boolean equals(java.lang.Object);
     public int hashCode();

     public final Class getClass();

     protected java.lang.Object clone()
                    throws CloneNotSupportedException;

     // methods relating to thread programming
     public final void notify();
     public final void wait() throws InterruptedException;
}

The “throws SomeException” clause is an announcement of the kind of unexpected error return that the method might give you. Object does have a few more methods than shown here. The API documentation has the full description.

Most of the methods in Object provide some useful, though often elementary, functionality. Programmers are supposed to write their own version of any of these methods to replace the basic one if necessary. When an object (any object) calls a method, its own version of that method is preferred over an identically named method in a parent class, as we'll see in Chapter 8. The technical term for this is overriding. Object makes sure there is a basic version of the methods; the programmer specializes them if necessary.

String toString();

This is a handy method. You can call it explicitly, and it will return a string that “textually represents” this object. It's actually the name of the class of the object, the “@” sign, and the address of the object. Use it while debugging to see if your objects really are what you thought they were. These lines in file ClockView.java will invoke Object's toString() on a Timestamp object, and print the String.

Timestamp t = new Timestamp();
t.fillTimes();
String s = t.toString();
System.out.println(s);

When you run the clock program with these lines, the output will have this general form (the actual number, being an address, will vary from system to system):

Timestamp@af9e22

Many programmers supply their own implementation of Object's toString() for some of their more important classes. They may put other debugging information into the string returned. Or they may make the toString() method provide a printable representation for output. Here is a such a method for Timestamp:

class Timestamp {
        int hrs;
        int mins;
        int secs;

        public String toString() {
            String result = Integer.toString(secs);
            if (secs<10) result = "0" + result;
            result = Integer.toString(mins) + ":" + result;
            if (mins<10) result = "0" + result;
            result = Integer.toString(hrs) + ":" + result;
            if (hrs<10) result = "0" + result;
            return result;
        }
  //  rest of class omitted

With this change, when you re-run the program, each time toString is called the output will look similar to:

13:24:42

boolean equals(Object obj)

If you compare two objects for equality using the “==” comparison, e.g. if (o1==o2) the reference variables are compared, not any of the contents of either object. If you think about it, that's exactly what you've written. The equals() method in Object is there to give you a “hook” to do a more sophisticated comparison.

As implemented in class Object, the equals() method does the same comparison of reference variables. Variables obj1 and obj2 compare equal if both point to the same object. You invoke it as here:

if (obj1.equals(obj2) ) /* more code */

If this is not adequate for one of your classes, supply your own version of equals to look at the fields of each object and do a more detailed comparison. For example, two Strings are usually considered equal if they contain the exact same sequence of characters. So String has an equals() method that iterates down one String, comparing all its characters with the characters in the other String.

int hashCode ()

A hashcode is a value that can be used to uniquely identify an individual object. The most natural implementation is to use the memory address of an object as its hashcode, since every object has a unique address.

The hashcode of an object is used as a key in one of the standard data structure classes—java.util.Hashtable. Although you might program for a long time without needing this, it turns out to be useful to be able to put any kind of object in a hashtable, should we so desire. Therefore we need to be able to get a hashcode for every single object in the system. So the method was put in the Object class.

When you provide your own version of equals() for your own class, you should also provide your own version of hashCode() for that class, to make sure that equal Objects get the same hashcode. If you fail to do this, your objects will mysteriously fail to work in some data structures in the Collections classes. Collections have their own chapter later on.

final Class getClass()

All class types have an object that represents them at run-time. This run-time representation is known as Run Time Type Identification or RTTI. The method getClass() gets that object containing the RTTI information, returning it in an object of type java.lang.Class.

Say you have an object pointer, o:

Object o;

At some point in execution, this can get assigned to point to different objects:

o = new Integer(27);

or

o = new Character('?'),

Using methods from java.lang.Class, you find out the actual more-specific class to which an arbitrary object belongs. You call the getClass method to do this:

Class whatAmI = o.getClass();

Application programmers rarely need to do this. It is intended for people writing compilers, IDEs and system programs.

Object clone() throws CloneNotSupportedException

Java supports the notion of cloning, meaning to get a complete bit-for-bit copy of an object. Java does a shallow clone, meaning that when an object has data fields that are other objects, it simply copies the reference. The alternative is to recursively clone all referenced classes, too, known as a deep clone.

As a programmer, you can choose the exact cloning behavior you want. If a class wants to support deep cloning on its objects, it can provide its own version of clone().

Application programmers do want to clone objects occasionally. Say you have an object representing a new customer who is buying something. You might clone the object representing the new customer so it can be added to the customer database in a separate thread. In the meantime, the original object is processed to complete the sale. That way, both tasks have all the data they need, and neither task has to wait for the other.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.206.112