File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

can't call another constructor from no-arg constructor

vitesse wei
Ranch Hand

Joined: Sep 07, 2007
Posts: 100
class test
public static void main( String [] args )
new test();
test(int x)


why i can not call test(2) in test()?

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

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...


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
sankar kandasamy

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
In the constructor test
this(2);// Here it calls the constructor test(int x)
test(int x){
// some process
Peter Mularien
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
I agree. Here's the link:
subject: can't call another constructor from no-arg constructor
It's not a secret anymore!