learningboy
learningboy

Reputation: 37

Every subclass in Java inherits from two classes (Object and its superclass)?

When I create a new class, it is

ClassA extends Object{
}

So, if I were to have ClassA inherit from ClassB, wouldn't it be

ClassA extends Object extends ClassB {
}

which is basically Multiple Inheritance that is not allowed in Java.

Or is there a special exception for the Object class, which means it is indeed, safe to say, that every base class in Java inherits from exactly 2 classes ?

Upvotes: 1

Views: 981

Answers (2)

Jason C
Jason C

Reputation: 40336

No.

It would be ClassA inherits from ClassB which inherits from Object.

This is not multiple inheritance. This is single inheritance. Single inheritance gives you sort of a chain:

Object -> ClassB -> ClassA

Multiple inheritance lets you do more of a tree:

Object -> ClassB \
                  ---> ClassA
Object -> ClassC /

Java doesn't let you do the latter. The closest you can get is implementing multiple interfaces.

Note that this is still OK (single inheritance), since each class has at most one direct base:

                  /--> ClassC
Object -> ClassB -
                  \--> ClassD

Also, to answer your direct question, JLS 8.1.4 states (emphasis mine):

Given a ... class declaration ... the direct superclass of the class type C ... is the type given in the extends clause of the declaration of C if an extends clause is present, or Object otherwise.

That is, it's still single inheritance. If you have an extends then that's the base class, otherwise the base is Object. In your example, ClassA does not have Object as a direct base.


You can experiment for yourself a little, too. Check out this example:

static class ClassB {
}

static class ClassA extends ClassB {
}

static void printHierarchy (Class<?> clz) {
    if (clz != null) {
        System.out.println(clz.getSimpleName());
        System.out.print("inherits from: ");
        printHierarchy(clz.getSuperclass());
    } else {
        System.out.println("nothing");
    }
}

public static void main (String[] args) {
    printHierarchy(ClassA.class);
}

Outputs:

ClassA
inherits from: ClassB
inherits from: Object
inherits from: nothing

Upvotes: 8

Eli Sadoff
Eli Sadoff

Reputation: 7308

Java does not support Multiple Inheritance. Instead what you are describing is a class heirarchy. All classes in Java that do not explicitly extend a class, extend Object. However, if a class A extends B, then it is not directly extending Object. Because B directly extends Object, A is still a child class of Object (as in you can do Object a = new A() without any problems), but it is not a direct subclass.

Upvotes: 1

Related Questions