• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can't call another constructor from no-arg constructor

 
vitesse wei
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code:
class test
{
public static void main( String [] args )
{
new test();
}
test(int x)
{
System.out.println(x);
}
test()
{
test(2);
}

}

why i can not call test(2) in test()?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vitesse wei:
...why i can not call test(2) in test()?

To call an overridden version of a constructor from within another constructor, use the keyword "this" along with the correct arguments. For example...

this(2);

Note that if you do this, it must be the first line of the constructor.
 
sankar kandasamy
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
we can call the construtor with parameter from no argument constructor
by using this keyword with in the same class
Example
In the constructor test
test(){
this(2);// Here it calls the constructor test(int x)
}
test(int x){
// some process
}
 
Peter Mularien
Author
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keep in mind though (this is commonly a "trick" question) that you can call a method with the same name as the constructor in the fashion you show:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic