| 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
|
 |
 |
|
|
subject: Calling constructors from constructors ( A small problem)
|
|
|