• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

can't call another constructor from no-arg constructor

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()?
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}
 
Author
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Tell me how it all turns out. Here is a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic