Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructing overloading

 
ishmayel vemuru
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Krishna Srinivasan
Ranch Hand
Posts: 1862
Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Hibernate Linux Spring
 
Krishnamoorthy Vuyala Muralidharan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic