• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors - defaulting this() or super()

 
Adam Crawford
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

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?

Thanks.
Adam.

 
Himai Minh
Ranch Hand
Posts: 1328
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(){} ?
No.

That is why it won't compile.
 
Adam Crawford
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic