Java Reference
In-Depth Information
Self-Test Exercises (continued)
17.
Suppose you add the following defi ned constant to the class Employee ( Display 7.2 ):
public static final int STANDARD_HOURS = 160; //per month
Would it then be legal to add the following method to the class HourlyEmployee
( Display 7.3 )?
public void setHoursToStandard()
{
hours = STANDARD_HOURS;
}
The Class Object
Java has a class that is an ancestor of every class. In Java, every class is a derived class of
a derived class of . . . (for some number of iterations of “a derived class of ”) of the class
Object . So, every object of every class is of type Object , as well as being of the type of its
class (and also of the types of all its ancestor classes). Even classes that you define yourself
are descendent classes of the class Object . If you do not make your class a derived class of
some class, then Java will automatically make it a derived class of the class Object .
The class Object allows you to write Java code for methods with a parameter of type
Object that can be replaced by an object of any class whatsoever. You will eventually
encounter library methods that accept an argument of type Object and hence can be
used with an argument that is an object of absolutely any class.
object
class
The Class Object
In Java, every class is a descendent of the class Object . So, every object of every class is
of type Object , as well as being of the type of its class.
The class Object is in the package java.lang , which is always imported
automatically. So, you do not need any import statement to make the class Object
available to your code.
The class Object does have some methods that every Java class inherits. For example,
every object inherits the methods equals and toString from some ancestor class,
which either is the class Object or a class that itself inherited the methods ultimately
from the class Object . However, the inherited methods equals and toString will
not work correctly for (almost) any class you define. You need to override the inherited
method definitions with new, more appropriate definitions.
It is important to include definitions of the methods toString and equals in the
classes you define, because some Java library classes assume your class has such methods.
There are no subtleties involved in defining (actually redefining or overriding) the
method toString . We have seen good examples of the method toString in many of
our class definitions. The definition of the overridden method equals does have some
subtleties; we discuss them in the next subsection.
toString
equals
 
Search WWH ::




Custom Search