File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes This and Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "This and Constructor" Watch "This and Constructor" New topic

This and Constructor

Frances Hollis

Joined: Sep 02, 2006
Posts: 17
I need to write an constructor using 'this'. I understand the concept but I don't get the syntax.

Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
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 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

Joined: Sep 26, 2006
Posts: 148

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:


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

Joined: Aug 25, 2006
Posts: 1274
Hi cowboys,

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

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.
this(parameter); // must fit to an existing constr.



all events occur in real time
I agree. Here's the link:
subject: This and Constructor