This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
A constructor must have this(arguements, if any) or super(arguements, if any) as the first statement of any constructor, but not both. The VM inserts a no-arg super() for us. But if we use this(), then it doesn't.
Joined: May 17, 2005
Sid I am not asking about this(). Lets say the below is an example
Agree with Svend Rost that this is permissible in a constructor.
The snippet you quote with School.addStudent(this); is legal syntax, but has several potential bad bits of programming in:
The constructor is for setting up the Student object, not for updating the School object, which is what you are doing here.
You should be adding to the School in the School object.
Better Now, there are two possible uses of "this" in a Java constructor. One is where you have several overloaded constructors, and you use "this" to call the other constructors. Example (amended from Deitel and Deitel 6th Edition page 366f)As Sidd Cool has said, you can only use this( . . . ); or super( . . . ); as the first statement in the constructor, so you can't use both in the same constructor.
As for using this. in a constructor, well there are several ways to set up a constructor.
BEWARE: Two of the constructors shown below contain serious logic errors. I shall let the readers work out which. Let's look at this class:-Type 1:Type 2:Type 3:Type 4:Type 5Type 1 has the drawback that you chose a proper name for the fields, and in the public interface of the class you are exposing the useless little names of "p" and "b." In 2 and 3 you have actually get a better name for the initial balance. Type 4 is what you would get from the Eclipse IDE if you set up the fields, then click Source->Create Constructors from Fields.
I think the best form for this particular constructor would be this sort of thing:- I hope this goes some way to answering your query. CR [Edited for minor spelling and formatting errors] [ February 26, 2007: Message edited by: Campbell Ritchie ]
Calling on a dim memory that says "Don't do that!" I think the little example
is a dangerous practice because we are not guaranteed that "this" is completely set up and safe to use until the constructor returns. School might start calling methods on the Student before Student is fully initialized.
What if somebody extends Student?
School could call Student methods before StarStudent is ready. The short guideline is don't expose yourself before you're fully dressed. [ February 26, 2007: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi