Skip to main content

Subclass Constructors

2 replies [Last post]
Joined: 2008-11-29


I've got a question regarding the tutorial "Learning the Java Language", chapter "Interfaces and Inheritance", section "Using the Keyword super" where it says:

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

I have declared a class Parent, class Child extends Parent and class Grandchild extends Child with no constructors in none of them, so I expected a compile-time error in Child and Grandchild (as their superclass wasn't Object), but it all compiled and executed just fine. So is there an error in the tutorial, or did I missunderstand something? Thank you.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-05-06

Hi Skyrider,

If you do not declare a constructor in a class, you get a zero-argument constructor by default. Therefore:

- Parent gets a default zero argument constructor which calls Object's zero argument constructor.
- Child gets a default zero argument constructor which calls Parent's zero argument constructor - this exists so no compile error.
- Same for Grandchild calling Child's zero-arg constructor.

If, for example, Parent had a constructor that required arguments, Child would then not compile because Child's [i]generated[/i] zero-argument constructor can only call a zero-argument superclass constructor. In this case you would have to write a constructor for Child with a super() call that has Parent's required arguments.

Joined: 2008-11-29

Hi Prunge,

thanks for the explanation. Now I see the difference between "no constructor" and "no-argument constructor" in a class.