-
constructor code
Hello
I have been reading a java a book. and the writer puts a lot of code in his constructors. Can someone tell me if this is good practice. An example is below.
I thought that constructors were just for initializing variables, and should not include a lots of code. Maybe l am wrong?
Can someone tell me if the code below is ok to put into a constructor.
Code:
public class Beaufort
{
//instance variables
float speedOfWind = 0.0f;
int force = 0;
String beaufortDiscription;
//constructor
public Beaufort(float windSpeed)
{
speedOfWind = windSpeed;
if (speedOfWind == 0)
{
beaufortDiscription = "Calm";
force = 0;
}
else if (speedOfWind <= 4)
{
beaufortDiscription = "Light air";
force = 1;
}
else if (speedOfWind <= 7)
{
beaufortDiscription = "Light breeze";
force = 2;
}
else if (speedOfWind <= 11)
{
beaufortDiscription = "Gentle breeze";
force = 3;
}
else if (speedOfWind <= 18)
{
beaufortDiscription = "Moderate breeze";
force = 4;
}
else if (speedOfWind <= 24)
{
beaufortDiscription = "Fresh breeze";
force = 5;
}
else if (speedOfWind <= 31)
{
beaufortDiscription = "Strong gale";
force = 6;
}
else if (speedOfWind <= 38)
{
beaufortDiscription = "Near gale";
force = 7;
}
else if (speedOfWind <= 46)
{
beaufortDiscription = "Gale";
force = 8;
}
else if (speedOfWind <= 54)
{
beaufortDiscription = "Strong Gale";
force = 9;
}
else if (speedOfWind <= 63)
{
beaufortDiscription = "Storm";
force = 10;
}
else if (speedOfWind <= 73)
{
beaufortDiscription = "Violent storm";
force = 11;
}
else if (speedOfWind >= 74)
{
beaufortDiscription = "Hurricane";
force = 12;
}
}
public int windForce()
{
return force;
}
public String description()
{
return beaufortDiscription;
}
}
Many thanks in advance
Steve
-
What he has done is perfectly legal. He could have just as easily initialized the windspeed variable with the constructor and placed the conditional code in an alternate method.
Also....... seems like he has his relational operators mixed up. Unless you copied incorrectly. The last else if seems right.
-
Hello
The relational operators are ok, i have tested this program and everything works fine.
Just one quick question, how much code can you put in a constructor?
Thanks in advance
Steve
-
A constructor is a completly normal function, except that it has no return value and can't be called directly.
Therefore you can have as much code as you want in the constructor.
A constructor is not just for initializing variables, it's for initializing the class. If that means lots of code, that's ok.
Note however that, because constructors often have overloads and constructor chaining is somwhat problematic, it's good practice to put most of the code into a private function and call that function from the various constructors.