9.11. The protected Data and Methods

 
[Page 310 ( continued )]

9.6. The Object Class and Its toString() Method

Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object by default. For example, the following two class declarations are the same:

Classes like String , StringBuffer , Loan , and GeometricObject are implicitly subclasses of Object (as are all the main classes you have seen in this book so far). It is important to be familiar with the methods provided by the Object class so that you can use them in your classes. This section introduces the toString() method. Other methods will be introduced in §9.13.

The signature of the toString() method is

  public  String toString() 


[Page 311]

Invoking toString() on an object returns a string that represents the object. By default, it returns a string consisting of a class name of which the object is an instance, an at sign (@), and the object's hash code in hexadecimal. For example, consider the following code for the Loan class defined in Listing 7.9:

 Loan loan =   new   Loan(); System.out.println(loan.toString()); 

The code displays something like Loan@15037e5 . This message is not very helpful or informative. Usually you should override the toString method so that it returns a descriptive string representation of the object. For example, the toString method in the GeometricObject class in Listing 9.1 was overridden as follows :

   public   String toString() {   return   "color: "   + color +   "and is filled: "   + filled; } 

Note

You can also pass an object to invoke System.out.println(object) or System.out.print(object) . This is equivalent to invoking System.out.println(object.toString()) or System.out.print(object.toString()) . So you could replace System.out.println(loan.toString()) with System.out.println(loan) .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net