wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can't call another constructor from no-arg constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can Watch "can New topic
Author

can't call another constructor from no-arg constructor

vitesse wei
Ranch Hand

Joined: Sep 07, 2007
Posts: 100
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()?


SCJP 5.0<br />SCWCD1.4<br />SCBCD5
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
sankar kandasamy
Greenhorn

Joined: Sep 13, 2007
Posts: 13
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

Joined: Sep 06, 2007
Posts: 84
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:


Author, Spring Security 3 (the Book), Packt Publishing, 2010
SCJP, OCP
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can't call another constructor from no-arg constructor