File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors - defaulting this() or super() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors - defaulting this() or super()" Watch "Constructors - defaulting this() or super()" New topic

Constructors - defaulting this() or super()

Adam Crawford

Joined: Feb 27, 2012
Posts: 9

I have the following piece of code:

This doesn't compile unless I either replace "#1" with: public A() {}; or replace #2 with: public B(String s) { super(s); };

In the SCJP study guide it states:"Every constructor has as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler. If you do type in a constructor (as opposed to relying on the compiler-generated default constructor), and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor".

I was expecting the constructor for Class A to have "super()" inserted by the compiler which I thought would then call Object.

Can someone please explain what actually happens and why it compiles if #1 or #2 are inserted?


Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 1118
In your example, class A does not have an non-arg constructor. When you define an arg constructor, there is no non-arg constructor.
In class B , there is a default constructor implicitly defined : B(){} even though you don't define it.
So, what is inside B() by default?

But does class A has a default constructor, A(){} ?

That is why it won't compile.
Adam Crawford

Joined: Feb 27, 2012
Posts: 9
Of course!

I was so busy concentrating on Class B, I didn't see that Class A was without a constructor and forgot the golden rule that a default constructor is inserted by the compiler.

All makes sense now - thanks very much!
I agree. Here's the link:
subject: Constructors - defaulting this() or super()
jQuery in Action, 3rd edition