问题
I'm new to Java, so I'm sure this is an easy question (my head is spinning from studying all day long). Here's the code I'm studying and can't remember/figure out what this line of code is doing:
public Temperature(String type, double degrees) {
if (type.equalsIgnoreCase("C"))
Is this considered a constructor? What are the two parameters "String type, double degrees" doing? tia.
Here's the code from the top down:
public class Temperature {
private double degreesFahrenheit; // Fahrenheit temperature
private double degreesCelsius; // Celsius temperature
private double degreesKelvin; // Kelvin temperature
/** * This constructor for Temperature sets the temperature
* values to the value from degrees, based on the type *
* @param type temperature scale to use
* @param degrees degrees Fahrenheit
*/
public Temperature(String type, double degrees) {
if (type.equalsIgnoreCase("C"))
setDegreesCelsius(degrees);
else if (type.equalsIgnoreCase("F")) setDegreesFahrenheit(degrees);
else if (type.equalsIgnoreCase("K")) setDegreesKelvin(degrees);
...
回答1:
Yes! This:
public Temperature(String type, double degrees){
...
}
is a constructor.
Basically what it does when called is to create a new Temperature object and set some fields in the class by:
1) Check if the arguement type is C or c, F or f, K or k and
2) appropriatelly call the methods:setDegreesCelsius(degrees); , setDegreesFahrenheit(degrees); and setDegreesKelvin(degrees); respectivelly.
You haven't posted the code for those methods but its most likely that:
if the input is C you assign degreesCelsius; the value of the degree arguement of your constructor.
Similarly if F to the degreesFahrenheit; and if Kto the degreesKelvin;
The definition of these methods probably looks like this:
setDegreesCelsius(double degrees){
this.degreesCelsius = degrees;
}
Hope this helps.
Update after your comment:
public Temperature(String type, double degrees) that the constructor only accepts 2 arguements. a String and a double. There are there so that you can create a Temperature instance and also set the values of some fiels.
For example this code :
Temperate x = new Temperature("C", 35); means that x is a Temperature object and counts in the Celcious scale, and the current temperature is 35.
Hope this makes more sense
来源:https://stackoverflow.com/questions/25775088/using-a-constructor-statement-constructor