aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Super and this within same method/constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Super and this within same method/constructor" Watch "Super and this within same method/constructor" New topic
Author

Super and this within same method/constructor

Swati Singhal
Ranch Hand

Joined: Dec 08, 2003
Posts: 31
please explain:
1. Can we have both super() and this within the same method/constructor??
2. I read it's not possible, but when i tried running the following code, it runs fine:

Can somebody throw some light on this?
Bijesh Krishnadas
Ranch Hand

Joined: Aug 08, 2002
Posts: 31



Can somebody throw some light on this?

Swati,
u cannot use super( <args> ) and this( <args> ) within the same constructor.
NOTE: super( <args> ) invokes a constructor in the parent and this( <args> ) is used to invoke another constructor within the same class.
In your code above u access the super() constructor invocation and the this object (not the constructor call). perfectly legal.
Bijesh
[ March 19, 2004: Message edited by: Bijesh Krishnadas ]
[ March 19, 2004: Message edited by: Bijesh Krishnadas ]
RaviKumar Golagani
Greenhorn

Joined: Sep 02, 2003
Posts: 15
Hi Swati,
Even I too read that both super() and this() cannot be placed in the constructor, thanks for posting this Qn even me too was in same impression.
But they both can be in the same constructor, just make sure that super() must be the first statement to be placed in the constructor, or else it may throw a compile time error.
Cheers
Ravi
Swati Singhal
Ranch Hand

Joined: Dec 08, 2003
Posts: 31
Thanks Bijesh. I am clear about it now.
Bijesh Krishnadas
Ranch Hand

Joined: Aug 08, 2002
Posts: 31
Originally posted by RaviKumar Golagani:
Hi Swati,
.....
But they both can be in the same constructor, just make sure that super() must be the first statement to be placed in the constructor, or else it may throw a compile time error.
.....

Ravi,
I think u misunderstand. super() and this() cannot be present in the same constructor. In swati's code we don't have super() and this() in the same constructor. We have only super(), this is used just as an object.
Use of both super() and this() are restricted by the condition that they can be used only as the first statement of a constructor. Both cannot be the first statement at the same time and so cannot be used together in the same constructor.
Am I making this too confusing?
Bijesh
RaviKumar Golagani
Greenhorn

Joined: Sep 02, 2003
Posts: 15
Hi Krishnadas
Yes, I was in a overlook....
Thanks
Ravi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Super and this within same method/constructor