• Post Reply Bookmark Topic Watch Topic
  • New Topic

call to super() and this() - k&b p139  RSS feed

 
Kiran Gavate
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

In k&b p139 I have been reading that a constructor can never have a call to super() and a call to this() because either needs to be the first statement in a constructor.

Also it has been stated that -

'That also means the compiler will not put a call to super() in any constructor that has a call to this()'

But I am not able to verify this. e.g. if I run the following code -



I get the following output -

In Super constructor...
In SuperTest no-args constructor...
In Super constructor...
In SuperTest no-args constructor...
In SuperTest(String s) constructor...

It looks like the compiler Is putting a call to super() even when the constructor SuperTest(String s) has a call to this().

Could somebody please explain if I am doing something wrong here?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing wrong, this is perfectly normal behaviour.

1. SuperTest(String s) calls this(), which means it calls the constructor SuperTest()

2. SuperTest() implicitly calls super() (which translates to SuperSup())

You can think of it like this: An object of type SuperTest consists of a SuperSup object plus something extra (the extra stuff in SuperTest, which extends SuperSup). So if you create a SuperTest object, the SuperSup object that is the base part of the SuperTest object has to created too. So at some point, a constructor of SuperSup has to be called.
 
Kiran Gavate
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jesper,

It means that the super constructor will ALWAYS be called no matter what.
whether inserted by the compiler explicitly or through a call to this().
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kiran Gavate:

It means that the super constructor will ALWAYS be called no matter what.
whether inserted by the compiler explicitly or through a call to this().


An instance of the SuperTest class IS-A SuperSub object, so at some point, the part of the object that is being inherited has to be contructed too.

Henry
[ January 26, 2007: Message edited by: Henry Wong ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!