This is a discussion on Java Package-java.lang.Object within the Programming forums, part of the Tutorials category; Java Package-java.lang.Object The Object class is the base class from which all further Java classes are derived. This makes Java ...
Java Package-java.lang.Object
The Object class is the base class from which all further Java classes are derived. This makes Java a single typed language; i.e., all defined types derive from a single common predecessor. All classes derive from Object whether it is explicitly stated or not. For instance, consider the following class declarations:
public class AquaMonster
public class AquaMonster extends Object
Both declarations declare an AquaMonster class; and, yes, both inherit their functionality from the Object class. The two declarations are semantically very similar. If a class does not explicitly extend any other known class, then the compiler will automatically insert extends Object in the class declaration. Classes that extend classes other than the Object class are still of type Object themselves. For instance, here is the header for a fictitious Hydra class:
public class Hydra extends AquaMonster
Therefore, you can see the “is-a” relationship reaches up the entire ladder of inheritance. So, who cares that the “is-a” relationship extends up the hierarchy ladder? Well, it makes a world of difference when you want to write generic, flexible code. For instance, the below Example 1 used the Arrays sort method to sort an array of String objects. The sort method took a Comparator object as its second argument. The Comparator interface, in turn, has one method, the compare method. The compare method then takes two Object parameters to compare, as the following header shows:
public int compare(Object a, Object b)
Since every class you write extends Object, you can send any class type to the compare method. If you didn’t have Object as a root base class, then you would have to define a different compare method for every possible class you can think of: String, Dog, Cigar, ReflectPermission, Hydra—the list goes on forever. In short, the removal of the Object class from the Java language would significantly cut down on its ability to allow for rapid, flexible development.
Example 1:
import java.util.*;
public class SortTest extends Object
{
public static void main(String[] args)
{
// create some Integer values
Integer[] values = { new Integer(670), new Integer(90),
new Integer(-23), new Integer(0),
new Integer(2), new Integer(659),
new Integer(1), new Integer(-40) };
// sort the values
Arrays.sort(values);
// print the sorted array to the console
for(int i = 0; i < values.length; i++)
{
System.out.println(values[i]);
}
}
} // SortTest
Bookmarks