aspose file tools*
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
Author

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);
t.call1();
}
void call1()
{
call2(); // line 10
}
void call2()
{System.out.println("call2");}
testCon()
{ testCon(2); // line 13 }
testCon(int x)
{ System.out.println(x); }

}

Out put :
>java testCon
2
call2



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..
Ishmayel.
Matt Russell
Ranch Hand

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

with

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

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

Joined: Jul 28, 2003
Posts: 1844

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:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#367


Krishna Srinivasan
Spring Tutorials, OCAJP Mock Questions, 400+ OCPJP Mock Questions
Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 791

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
Hi

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
Kris
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructing overloading