• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Calling constructors from constructors ( A small problem)

 
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
 
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
 
Curse your sudden but inevitable betrayal! And this tiny ad too!
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic