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 Constructing overloading 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 "Constructing overloading" Watch "Constructing overloading" New topic

Constructing overloading

ishmayel vemuru
Ranch Hand

Joined: Jun 13, 2007
Posts: 46
Hi to all..
I am getting the compilation error when I called the one argument constructor from the zero argument constructor.. why ?

public class testCon
public static void main( String [] args )
testCon t=new testCon(2);
void call1()
call2(); // line 10
void call2()
{ testCon(2); // line 13 }
testCon(int x)
{ System.out.println(x); }


Out put :
>java testCon

Why I am getting the compilation error at line 13 why not at line 10.
Please explain me If any one had Idea..
thanks in advance..
Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
The syntax to chain constructors is to use this, so replace:


and the code will compile.
[ June 14, 2008: Message edited by: Matt Russell ]

Inquisition: open-source mock exam simulator for SCJP and SCWCD
Krishna Srinivasan
Ranch Hand

Joined: Jul 28, 2003
Posts: 1850

You have to use this() when you are calling the another constructor inside a constructor. try the below code. it will work:

also read coding conventions for java class name:

Krishna Srinivasan
OCAJP 7/8 Exam, 400+ OCPJP Mock Questions
Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 802

use this()

SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
Krishnamoorthy Vuyala Muralidharan
Ranch Hand

Joined: Sep 13, 2005
Posts: 52

if you need to call the overloaded constructors from other constructors you must use this() or this(arguments...) depending on what you need. Instead if you try to call the overloaded constructor as 'testCon(2);' (as you did) then the compiler complains as it will not find any method definition 'testCon8(int arg)' in your class definition. That is the reason why you get the compiler-error.

Hope this is clear.

Best Regards
I agree. Here's the link:
subject: Constructing overloading
It's not a secret anymore!