2.12 The Object Class2.11 Generic Methods2 Java with Caffeine2.13 Method Overriding

2.12 The Object Class

As already stated, all classes are derived ultimately from the Object class. If a class declaration omits the extends clause, it is derived from the Object class by default, i.e., the following two declarations are equivalent.

  class Class
  {
    ...
  }

  class Class extends Object
  {
    ...
  }

Class Object is declared in package java.lang; it has various methods that are not yet of interest to us.

The most important use of the Object class is the use as a parameter type in generic methods such that the method can operate on objects of any type.

For instance, we may implement a class Stack which can store objects of any object type as follows:

   class Stack
   {
     int N = 100;
     Object[] stack = new Object[N];
     int n = 0;

     void push(Object o)
     {
        if (n == N) resize();
        stack[n] = o;
        n++;
     }

     Object pop()
     {
       n--;
       return stack[n];
     }

     void resize() { ... }
   }

We may use this stack then to store Integer objects as in

   Stack s = new Stack();
   s.push(new Integer(2));
   s.push(new Integer(3));
   Integer i = (Integer)(s.pop());

Please note that the result of pop is an object, i.e., the caller has to cast it back to Integer. If the stack holds objects of multiple types, the caller may use the operator instanceof to select among these types:

   Stack s = new Stack();
   s.push(new Integer(2));
   s.push("hello");
   Object o = s.pop();
   if (o instanceof Integer)
   {
     Integer i = (Integer)o;
     ...
   }
   else if (o instanceof String)
   {
     String s = (String)o;
     ...
   }

Various container classes in the Java standard library (e.g. class Vector) operate in this fashion on arguments of type Object.


© Wolfgang Schreiner; February 3, 2005

2.12 The Object Class2.11 Generic Methods2 Java with Caffeine2.13 Method Overriding