Win a 3 month subscription to Marco Behler Videos this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructor Question  RSS feed

 
Herbert Morriss
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want multiple constructors. I am trying to get one constructor to call another but keep getting an error. Why cann't I do this?


public class Constructors
{
int x ;
String y ;

public Constructors( int x, String y)
{
this.x = x ;
this.y = y ;
}

public Constructors( int x )
{
String z = Integer.toString( x ) ;
Constructors( x , z ) ;
}
}


E:\Java\Sandbox\Constructors.java:18: cannot find symbol
symbol : method Constructors(int,java.lang.String)
location: class Constructors
Constructors( x , z ) ;
^
1 error

Tool completed with exit code 1
 
Henry Wong
author
Sheriff
Posts: 23260
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Herbert Morriss:
I want multiple constructors. I am trying to get one constructor to call another but keep getting an error. Why cann't I do this?


Two issues... First to call another constructor, you used this(). Second, a contructor can only call another constructor as the first call. So, in this case, you constructor should look like this...



Henry
 
Herbert Morriss
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!