• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors Problem

 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to know the reason for this,
If i write my code like this,
public static void main(String[] ghjhdgf)
{
ConstructorTest co = new ConstructorTest("s","s1","s2");
}

public ConstructorTest(String s,String s1)
{
System.out.println("No probs");
}

public ConstructorTest(String s,String s1,String s3)
{
this(s,s1);
}
It compiles fine ,but if i replace the constructor with 3 params in this way ,
public ConstructorTest(String s,String s1,String s3)
{
ConstructorTest(s,s1);
}
It does not compile.
Says no method of this signature in this class.
Thanks in adv,
Chinmay.
 
Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, the problem lies in the fact that Java allows methods with the same name as the class. So when you made the call:
ConstructorTest(s,s1);
The compiler thought that you wanted to call a method not another constructor. The only way a constructor will be called is:
1. with new keyword
2. with this(..)
3. with super(..)
(note: not including String = "dd")
so that is why you want to use, this(s1,s2).
Just to let you know you can change the line
ConstructorTest(s,s1);
to
new ConstructorTest(s,s1);
and it compiles fine.

Hope this helps
 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ibrahim.
Ur ans helped me understand this problem.
Chinmay..
 
Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem...thats what this place is for.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic