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 366
f)
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 5
Type 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 ]