• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling constructors from constructors ( A small problem)  RSS feed

 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello , this is in reference to a code given by Bruce Eckel's to understand how "Calling constructors from constructors" work

class Flower
{

private int petalCount = 0;
private String s = new String("null");



Flower(int petals)
{
petalCount = petals;
System.out.println("Flower(int petals) "+ petalCount);

}



Flower(String ss)
{
System.out.println("Flower(String ss) " + ss);
s = ss;
}



Flower(String s, int petals)
{

//System.out.println("Welcome to JavaRanch");
this(s);// Can't call two!
//this(petals);
this.s = s; // Another use of "this"
System.out.println("Flower(String s, int petals)");

}



Flower()
{
this("hi", 47);
System.out.println("Flower() ");

}



void print()
{
// ! this(11); // Not inside non-constructor!
System.out.println("petalCount = " + petalCount + " s = " + s);
}


public static void main(String[] args)
{
Flower x = new Flower();
x.print();
}
}


I can understand why we can't have 2 this() in the same constructor ,
Besides if comment out the line

//System.out.println("Welcome to JavaRanch");

The compiler will give me an error .
***call to this must be first statement in constructor
 
Dani Atrei
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's your question?
The call to another constructor within a constructor has to be the first statement in the constructor.

Dani
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!