Home arrow static arrow Java Programming [Archive] - Using the 'this' keyword in class constructors
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Using the 'this' keyword in class constructors
This topic has 4 replies on 1 page.

Posts:22
Registered: 6/21/04
Using the 'this' keyword in class constructors  
Jun 21, 2004 3:13 AM



 
Hi Everyone,

I have a class called Queue that I modified from a Java Certification text and it uses the this keyword in one of the various constructors provided. The code looks like this:

import java.util.Vector; class Queue extends Vector{	public static void main(String[] args)	{		String[] myCoolStrings = {"The", "cat", "ran", "over", "the", "mat"};		Queue myPoolQueue = new Queue(myCoolStrings); 		for(int i=0; i<myCoolStrings.length; i++)		{			String currentString = (String)myPoolQueue.dequeue();			System.out.print(currentString);						if(currentString.equals("mat"))			{				System.out.print(".");				System.out.println();			}			else			{				System.out.print(" ");			}		}			}	 	Queue()	{		super();	} 	Queue(int capacity)	{		super(capacity);	} 	Queue(int capacity, int increment)	{		super(capacity, increment);	} 	Queue(Object[] objs)	{		this(objs.length); //here is the use of this! :)		for(int index = 0; index < objs.length; index++)		{			addElement(objs[index]);		}	}  	void enqueue(Object obj)	{		addElement(obj);	} 	Object dequeue()	{		Object obj = firstElement();		boolean success = removeElement(obj);		return obj;	}}

I figure that the "this" keyword is somehow able to "look up" the class hierarchy and see that there is a constructor that accepts an integer argument in the superclass. I may be completely off here, I really don't understand how this code works. If anybody could explain to me how this works I will be very appreciative. If you don't have the time to explain yourself, but know where I can find out more about using 'this" in constructors, that would be great also. Thanks heaps for your help.

Regards

Davo
 

Posts:5,119
Registered: 16.08.01
Re: Using the 'this' keyword in class constructors  
Jun 21, 2004 3:40 AM (reply 1 of 4)



 
Okay, here are the rules for constructors--"ctors" because I'm lazy. Also, because I'm lazy, "super(...)" and "this(...)" mean any super or this call, regardless of how many args it takes, including those that take no args.

1) Every class has at least one ctor.

1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().

1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a
public MyClass() {...} 
if you want one.

1.3) Constructors are not inherited.

2) The first statement in the body of any ctor is either a call to a superclass ctor
super(...) 
or a call to another ctor of this class
this(...) 


2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor
super() 
as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.

2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.
 

Posts:22
Registered: 6/21/04
Re: Using the 'this' keyword in class constructors  
Jun 21, 2004 8:46 PM (reply 2 of 4)



 
PhHein,

Thanks heaps for the heads up on constructors. I am still confused however as to what this is actually doing! It may be something really obvious that I have overlooked, or it could be that I am just confused, but either way I really don't understand what this is doing! Could you please provide some more helpful tips.

Thanks

Regards

Davo
 

Posts:5,965
Registered: 5/17/03
Re: Using the 'this' keyword in class constructors  
Jun 21, 2004 9:48 PM (reply 3 of 4)



 
If anybody could
explain to me how this works I will be very
appreciative. If you don't have the time to explain
yourself, but know where I can find out more about
using 'this" in constructors, that would be great
also.

It's called explicit constructor invocation. This() is used to invokes another constructor in the same class. Super() is ised to invoke another constructor in an extended class.

I usually check things like these out in a book called the Java Programing Language by Gosling and others. It's like a language definition but isn't that dense and it contains lots of background wiki/./information and advice on usage.
 

Posts:8
Registered: 6/3/04
Re: Using the 'this' keyword in class constructors  
Jun 21, 2004 9:48 PM (reply 4 of 4)



 
Ctors can also be overloaded as normal methods, so you can define multiple ctors of a class which take different args

"this" refers to your current instance, and any calls to "this(..)" maps to the corresponding ctor in your class.
and calls to "this(...)" are resolved by the compiler itself ( as it is done for normal overloaded methods)

For example .
public class A{      public A(int i)      {       // some code.....      }       public A(int i, char c)      {          this( i );==============> Maps to a call to A(int i)          // some code....       }}

Also since ctors are never inherited a ctor corresponsding to "this(..)" call should be defined explictly in your class, otherwise the compiler will give you error.
 
This topic has 4 replies on 1 page.