Search code examples
javaclassoopconstructorsubclass

If a subclass has no constructor, and neither does the superclass, then why can I construct an instance of the subclass?


From https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html: "You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does."

In the following code, class Goblin has no constructor. Neither does its superclass, Humanoid.

public class Humanoid {
    int weight;

    //public Humanoid() {
        //weight = 10;
    //}
}

class Goblin extends Humanoid {
    char armorColor;
}

class Driver {
    public static void main(String[] args) {
        Goblin grug = new Goblin();
        System.out.println(grug.armorColor);

        boolean isGrugAGoblin = false;
        isGrugAGoblin = (grug instanceof Goblin);
        System.out.println(isGrugAGoblin);
    }
}


I compiled and ran the above code successfully, despite the tutorial's claim that the compiler would complain. The output was


true

I expected an error, like the tutorial claimed. Is the tutorial wrong?


Solution

  • Every class in Java inherits, ultimately, from java.lang.Object. That is why your class has methods such as equals and toString.

    When you instantiate any class, an implicit call is made to its immediate superclass, and the immediate superclass of that, onwards to eventually reach Object.

    In your case, Humanoid extends java.lang.Object.

    class Goblin has no constructor

    Incorrect.

    The class Goblin has no explicit constructor. It does have an implicit constructor. Think of it as the compiler writing the constructor on your behalf, behind your back.

    For more info, see this Answer by OrangeDog to the Question, Java default constructor.

    Neither does its superclass, Humanoid

    Ditto. Humanoid has an implicit default constructor.

    For all the details, see Section 8.8.9. Default Constructor of Java Language Specification.