Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

This and Constructor

 
Frances Hollis
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to write an constructor using 'this'. I understand the concept but I don't get the syntax.

 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The syntax is just like calling one of your methods. You might declare a no-argument method "foo" in your own class. Then how would you call it? foo() or this.foo() if you wanted to qualify it. Using this to invoke another constructor is pretty much the same. this() will invoke a no-argument constructor. this("Bob") will invoke a constructor that accepts a single String argument. The catch is the constructor has to actually exist.

In your example "this()" won't work because there is no no-argument constructor to be invoked. You have one other constructor, it accepts an int, String and a double. So you'll need to invoke it by using this(int, String, double) where you are passing valid arguments of those types.
 
sven studde
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


That constructor is shorthand for:



"this" is an object of type Student. The technical details go something like this: every class method is passed an invisble parameter which is the object that is calling the method. The name of that parameter is "this". You can explicitly use the "this" parameter inside a class method in situations like the following:



In the code above, the local age variable in the constructor hides the class member age variable, i.e. when you use "age" inside the method, "age" will refer to the age parameter. To access the object's member variable, you need to use:

this.age

In constructors, it can be handy to use "this" so you don't have to bother thinking up unique names for the constructor's parameters. Instead, you can name the parameter variables the same names as the member variables and use the syntax:

[ October 02, 2006: Message edited by: sven studde ]
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi cowboys,

there are two ways of using the keyword this in a constructor.

One:
Assign a member variable or method (and prevent shading of variables).


Two, and I think that's what Francis wanted to do:
Invoke a constructor from a constructor. You can call a constructor of the same class with "this".
You call another constructor with the matching parameter or matching parameter list.
This call must be the first line of the constructor.
Syntax:
this(parameter); // must fit to an existing constr.

Example:




Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic