aspose file tools
The moose likes Beginning Java and the fly likes Calling constructors from constructors ( A small problem) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Calling constructors from constructors ( A small problem)" Watch "Calling constructors from constructors ( A small problem)" New topic
Author

Calling constructors from constructors ( A small problem)

faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139
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

Joined: Feb 17, 2004
Posts: 73
What's your question?
The call to another constructor within a constructor has to be the first statement in the constructor.

Dani


Si altas son las torres, el valor es alto - Alberti
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Calling constructors from constructors ( A small problem)
 
Similar Threads
Constructor - Thinking In Java
Constructor - Thinking In Java
Constructor
An easy way to explain "Calling constructors from constructors"