Monday, 30 January 2012

Java - Is Object class implicitly inherited ?

Java API includes description of Object class as "Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class."

So the question comes Is Object class implicitly inherited ? 
API docs didn't say anything on this, documentation says the Object class is the root of the class hierarchy and every class has Object as a superclass .
It doesn't mean that Object class is inherited by every class , instead the behaviour is provided by compiler to make every class is a child of Object class.

Lets understand through code sample - source code A.java
class A {
    public String toString(){
        return "class A";
    }
}
class B extends A {
     public String toString() {
            return "class B";
        }
}
class C extends B {
     public String toString(){
            return "class C";
        }
}
Here I haven't extended Object class and still override toString() method of Object class.So does it mean compiler makes Object class inherited by class A and put it in byte code? Ahh...Need to dig into byte code.
No worry , will find out that too.

Here is the byte code - A.class
class A {
  // Stack: 1, Locals: 1
  A();
    0  aload_0 [this]
    1  invokespecial java.lang.Object() [8]
   .........................


   ..........................  
public java.lang.String toString();
    0  ldc <String "class A"> [16]
    2  areturn
      Line numbers:
        [pc: 0, line: 3]
      Local variable table:
        [pc: 0, pc: 3] local: this index: 0 type: A
}


B.Class

class B extends A {
 
  // Method descriptor #6 ()V
  // Stack: 1, Locals: 1
  B();
    0  aload_0 [this]
    1  invokespecial A() [8]
...............................
...............................
...............................

C.class
class C extends B {
 
  // Method descriptor #6 ()V
  // Stack: 1, Locals: 1
  C();
    0  aload_0 [this]
    1  invokespecial B() [8]
..................................................
..................................................
Here , Compiler puts no-arg constructor by itself though I haven't included in source code. And there is no extends keyword in top most class A which says A extends Object , although there is a call to java.lang.Object() in A.class's byte code but it is a call to super class's constructor. very similar to what you can see in Class B and Class C    1  invokespecial A() [8] 
so the result is  compiler won't add extends Object for any class and hence technically Object class is not inherited automatcially on the other hand since Object class's non private members are available to child classes(which is by definition inheriting already developed behaviour from parent class ) it is quite evident  that Object class is inherited in Child class.

Does Object class break multiple inheritance ?
e.g. class A{ } class B extends A{ } , does it mean class B extends A , Object
No, reason Object class is the superclass in class hierarchy e.g. Object->A->B and not the direct superclass of all the classes.
So if Class A extends Object and Class B extends A , implicitly class B inheriting Class Object also.

5 comments:

  1. I am not clear on your statement "the behaviour is provided by compiler"
    If Object class is not inherited then how the methods of Object class are available to A class like toString()?

    public class JTest {

    public static void main(String[] args) {
    JTest t = new JTest();
    System.out.println(t.toString());
    }

    }

    Output - JTest@3e25a5

    ReplyDelete
  2. Hi Praful ,

    Thanks for your comments.
    Compiler takes care of making Object class's method available to all the classes in java.As it is said that Object class is super class of all the classes.

    toString() method is a String representation of Object and output you are getting because default implementation of Object class's toString() method is : getClass().getName() + '@' + Integer.toHexString(hashCode())

    "The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object."

    public class JTest
    {
    public static void main(String[] args)
    {
    JTest t = new JTest();
    System.out.println(t.toString());
    }
    public String toString()
    {
    return "Hello JTest";
    }
    }

    ReplyDelete
    Replies
    1. Hi Folks,

      To me it seems the question and justification didn't meet at the end.

      However it raised a good fundamental question of what it means to us by saying java.lang.Object is a super class for any class written in Java.

      From Java Docs I found the below def

      "Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object."

      And by inheritence, for me it means re using non private members rather than writing them in every new class and spending testing time unnecessarily.

      And yeah, from the byte code it is still clear that Object class is super class for the very first simple class(which is not inheriting any other class) Chandra, it seems you have pasted de-compiled code, but not the byte code.. pls check the byte code it clearly shows a call to Object()!!!

      But still the question is the byte code of "class A" doesn't show "extends Object"!! I feel it is ok as the members of Object are implicitly inherited by any other class and "extend" keyword is avoided in bytecode to just make us feel 'yeah, java doesn't support multiple inheritence!' yet :)

      Delete
    2. @RaT - Good Catch..my understanding with respect to Byte Code was different and I have corrected it in my post.
      For me technically Object class is not inherited as there is no extends Keyword in class A 's byte code. However by going through definition of inheritance Object class is inherited implicitly.

      Delete
  3. Thanks for your comment on my blog Javarevisited I see you also have good blog, keep up the good work going.

    ReplyDelete